powershell - PowerShell:使用 Try-Catch 调用命令
问题描述
我正在使用以下代码来输出一批计算机的状态:
$Win2k8r2Computers = "Server1", "Server2", "Server3", "Server4"
$results = Invoke-Command -ComputerName $Win2k8r2Computers { #}
$props = @{}
Try {
<#If ($PSVersionTable.PSVersion.Major -eq "2") {
$props.Add('Message',"Server (Win2008r2) is currently running an incompatible version of PowerShell (v2.1)")
}#>
If (Get-Service | Where-Object { $_.Name -eq "W3SVC" } -ErrorAction Stop) {
$props.Add('Message', "IIS is installed (Win2008r2)")
}
Else {
$props.Add('Message', "IIS is NOT installed (Win2008r2)")
}
}
catch {
$props.Add('Message', 'Error: {0}' -f $_)
}
New-Object -Type PSObject -Prop $Props
}
除了 catch 似乎没有实际捕获并将错误返回到 $results 变量之外,它按预期工作。我错过了什么?
解决方案
在您当前的代码中,您仅将参数传递-ErrorAction
给Where-Object
. 因此,您只会捕获Where-Object
cmdlet 的错误。Get-Service
woud 仍然使用默认ErrorAction
值运行Continue
。
要将两者的 Get-Service
错误Where-Object
转换为可以捕获的终止错误,请传递-ErrorAction 'Stop'
给它们两者......
If (Get-Service -ErrorAction Stop | Where-Object { $_.Name -eq "W3SVC" } -ErrorAction Stop)
...或者(更有效地)$ErrorActionPreference
在脚本开头设置变量并删除-ErrorAction
参数:
$Win2k8r2Computers = "Server1", "Server2", "Server3", "Server4"
$results = Invoke-Command -ComputerName $Win2k8r2Computers { #}
$props = @{}
Try {
$ErrorActionPreference = 'Stop'
<#If ($PSVersionTable.PSVersion.Major -eq "2") {
$props.Add('Message',"Server (Win2008r2) is currently running an incompatible version of PowerShell (v2.1)")
}#>
If (Get-Service | Where-Object { $_.Name -eq "W3SVC" }) {
$props.Add('Message', "IIS is installed (Win2008r2)")
}
Else {
$props.Add('Message', "IIS is NOT installed (Win2008r2)")
}
}
catch {
$props.Add('Message', 'Error: {0}' -f $_)
}
New-Object -Type PSObject -Prop $Props
}
警告:
$ErrorActionPreference
被 PowerShell 脚本模块中的 cmdlet 忽略,除非他们特别注意处理它。请参阅此答案以获取一些见解。
但在这种情况下它可以工作,因为这两个 cmdlet 都是在 C# 模块中实现的。
推荐阅读
- azure-ad-b2c - 如何对 Azure AD B2C 自定义策略中的 RESTful 终结点响应进行故障排除
- javascript - 无法匹配除 ' 和 " 之外的任何字符的正则表达式
- javascript - Javascript:如何遍历值数组并创建表行
- flutter - 颤振变量未传入类小部件
- gekko - 如何设置 GEKKO 以从多个独立的数据集进行参数估计?
- r - 在跨列的 for 循环中运行 if 和 else
- shader - 具有非均匀倾斜的Godot着色器?
- python - 自动点击器代码不起作用(第一个项目)
- go - 如何在我的 CLI 中获取用户选择的标志
- python - 构建具有不同扩展名选择的文件路径