PowerShell模块开发入门指南

模块基础结构

1
2
3
4
# 创建模块目录结构
New-Item -Path MyModule\Public -ItemType Directory
New-Item -Path MyModule\Private -ItemType Directory
New-Item -Path MyModule\MyModule.psd1 -ItemType File

清单文件配置

1
2
3
4
5
6
@{
ModuleVersion = '1.0'
RootModule = 'MyModule.psm1'
FunctionsToExport = @('Get-SystemInfo')
RequiredModules = @('PSScriptAnalyzer')
}

函数导出实践

1
2
3
4
5
6
7
8
9
10
11
function Get-SystemInfo {
[CmdletBinding()]
param()

$os = Get-CimInstance Win32_OperatingSystem
[PSCustomObject]@{
OSName = $os.Caption
Version = $os.Version
InstallDate = $os.InstallDate
}
}

模块发布流程

1
2
3
4
5
6
7
8
9
# 生成模块清单
New-ModuleManifest -Path .\MyModule\MyModule.psd1 \
-Author 'YourName' \
-Description '系统信息获取模块'

# 发布到本地仓库
Publish-Module -Path .\MyModule \
-Repository LocalRepo \
-NuGetApiKey 'AzureDevOps'

显示、隐藏 PowerShell

在 WPF 之周中,有个朋友希望有个最小化 PowerShell 窗口的例子。

以下是一个快速实现该需求的 module。只要将以下代码复制粘贴到 Documents\WindowsPowerShell\Packages\PowerShell\PowerShell.psm1 即可。

$script:showWindowAsync = Add-Type –memberDefinition @"
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
"@ -name "Win32ShowWindowAsync" -namespace Win32Functions –passThru

function Show-PowerShell() {
$null = $showWindowAsync::ShowWindowAsync((Get-Process –id $pid).MainWindowHandle, 10)
}

function Hide-PowerShell() {
$null = $showWindowAsync::ShowWindowAsync((Get-Process –id $pid).MainWindowHandle, 2)
}

现在,您可以用这段代码来显示或隐藏 PowerShell:

Add-Module PowerShell
# Minimize PowerShell
Hide-PowerShell
sleep 2
# Then Restore it
Show-PowerShell

希望这篇文章有所帮助。
James Brundage[MSFT]

译者注:ShowWindowAsync() 的第二个参数取值范围可以参照 API 文档 ShowWindow function
本文国际来源