PowerShell帮助文档与错误处理全解析
立即解锁
发布时间: 2025-09-13 00:16:55 阅读量: 2 订阅数: 9 AIGC 

### PowerShell帮助文档与错误处理全解析
#### 1. 简单帮助:添加注释
在编写PowerShell脚本和函数时,添加帮助文档是非常重要的,它能帮助用户更好地理解和使用工具。这里介绍两种方式:注释式帮助和外部帮助文件。
注释式帮助是在脚本或函数开头插入特殊格式的注释,PowerShell会将其解释为帮助文件。以下是注释式帮助的一些优点:
- 与代码分离,可独立更新,是PowerShell的`Update-Help`命令的工作基础。
- 可以提供多种语言版本,为不同用户提供本地化的帮助内容。
- 能被PowerShell解析为对象层次结构,提供额外的功能,适用于更多场景。
然而,创建MAML(Microsoft Assistance Markup Language)文件比较困难。过去,人们会使用一些工具将内容复制粘贴到图形用户界面(GUI)中生成MAML文件,但这种方法很耗时。现在,推荐使用开源项目PlatyPS,它允许使用Markdown这种简单的标记语言编写帮助内容。Markdown是GitHub的原生标记语言,方便在GitHub上阅读和编辑帮助文件。PlatyPS可以将Markdown转换为有效的MAML文件,其他工具还能将Markdown转换为HTML,用于网页帮助。
如果从未为代码编写过帮助文档,PlatyPS可以分析代码并为Markdown帮助文件创建框架,框架中会包含所有参数,并尽可能填充已知信息,如哪些参数是必需的、哪些参数接受管道输入等。同时,PlatyPS还能帮助维护帮助文件,当代码中的参数发生变化时,它能更新现有的帮助文件。
#### 2. 实践:为函数添加注释式帮助
现在,我们来为`Set-TMServiceLogon`函数添加注释式帮助。
以下是函数的初始代码:
```powershell
function Set-TMServiceLogon {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,
ValueFromPipelineByPropertyName=$True)]
[string]$ServiceName,
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True)]
[string[]]$ComputerName,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[string]$NewPassword,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[string]$NewUser,
[string]$ErrorLogFilePath
)
BEGIN{}
PROCESS{
ForEach ($computer in $ComputerName) {
Write-Verbose "Connect to $computer on WS-MAN"
$option = New-CimSessionOption -Protocol Wsman
$session = New-CimSession -SessionOption $option `
-ComputerName $Computer
If ($PSBoundParameters.ContainsKey('NewUser')) {
$args = @{'StartName'=$NewUser
'StartPassword'=$NewPassword}
} Else {
$args = @{'StartPassword'=$NewPassword}
Write-Warning "Not setting a new user name"
}
Write-Verbose "Setting $servicename on $computer"
$params = @{'CimSession'=$session
'MethodName'='Change'
'Query'="SELECT * FROM Win32_Service " +
"WHERE Name = '$ServiceName'"
'Arguments'=$args}
$ret = Invoke-CimMethod @params
switch ($ret.ReturnValue) {
0 { $status = "Success" }
22 { $status = "Invalid Account" }
Default { $status = "Failed: $($ret.ReturnValue)" }
}
$props = @{'ComputerName'=$computer
'Status'=$status}
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
Write-Verbose "Closing connection to $computer"
$session | Remove-CimSession
} #foreach
} #PROCESS
END{}
} #function
```
任务要求至少添加以下内容:
- 摘要(Synopsis)
- 描述(Description)
- 参数描述(Parameter descriptions)
- 两个示例及描述
添加帮助后的代码如下:
```powershell
function Set-TMServiceLogon {
<#
.SYNOPSIS
Sets service login name and password.
.DESCRIPTION
This command uses either CIM (default) or WMI to
set the service password, and optionally the logon
user name, for a service, which can be running on
one or more remote machines. You must run this command
as a user who has permission to perform this task,
remotely, on the computers involved.
.PARAMETER ServiceName
The name of the service. Query the Win32_Service class
to verify that you know the correct name.
.PARAMETER ComputerName
One or more computer names. Using IP addresses will
fail with CIM; they will work with WMI. CIM is always
attempted first.
.PARAMETER NewPassword
A plain-text string of the new password.
.PARAMETER NewUser
Optional; the new logon user name, in DOMAIN\USER
format.
.PARAMETER ErrorLogFilePath
If provided, this is a path and filename of a text
file where failed computer names will be logged.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,
ValueFromPipelineByPropertyName=$True)]
[string]$ServiceName,
[Parameter(Mandatory=$True,
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True)]
[string[]]$ComputerName,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[string]$NewPassword,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[string]$NewUser,
[string]$ErrorLogFilePath
)
BEGIN{}
PROCESS{
ForEach ($computer in $ComputerName) {
Write-Verbose "Connect to $computer on WS-MAN"
$option = New-CimSessionOption -Protocol Wsman
$session = New-CimSession -SessionOption $option `
-ComputerName $Computer
If ($PSBoundParameters.ContainsKey('NewUser')) {
$args = @{'StartName'=$NewUser
'StartPassword'=$NewPassword}
} Else {
$args = @{'StartPassword'=$NewPassword}
Write-Warning "Not setting a new user name"
}
Write-Verbose "Setting $servicename on $computer"
$params = @{'CimSession'=$session
'MethodName'='Change'
'Query'="SELECT * FROM Win32_Service " +
"WHERE Name = '$ServiceName'"
'Arguments'=$args}
$ret = Invoke-CimMethod @params
switch ($ret.ReturnValue) {
0 { $status = "Success" }
22 { $status = "Invalid Account" }
Default { $status = "Failed: $($ret.ReturnValue)" }
}
$props = @{'ComputerName'=$computer
'Status'=$status}
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
Write-Verbose "Closing connection to $computer"
$session | Remove-CimSession
} #foreach
} #PROCESS
END{}
} #function
```
添加注释式帮助时,可以使用脚本编辑器的代码片段功能创建模板。同时,注释式帮助允许额外的空白行,这有助于提高代码的可读性,且不会影响生成的帮助文件。
#### 3. 理解错误和异常
在PowerShell中,有两种主要的不良情况:错误(errors)和异常(exceptions)。大多数PowerShell命令设计为一次处理多个任务,当其中一个任务出现问题时,PowerShell默认会继续处理其他任务,只是会发出错误信息。例如:
```powershell
Get-Service -Name BITS, Nobody, WinRM
```
由于不存在名为“Nobody”的服务,PowerShell会针对该项目发出错误信息,但默认情况下会继续处理列表中的第三个项目。在这种“继续执行”模式下,代码无法对问题做出响应。如果需要对问题进行处理,就必须改变PowerShell对非终止错误的默认响应。
PowerShell定义了一个全局变量`$ErrorActionPreference`,用于指定在发生非终止错误时的处
0
0
复制全文
相关推荐









