我正在尝试使用Try-Catch运行一个相当简单的Powershell脚本,但我仍然遇到错误。
脚本:
foreach ($computerName in $computerNames) {
try {
$ie = Get-RegValue -ComputerName $computerName.Name -Key "Software\Microsoft\Internet Explorer" -Value Version
if ($ie.data -eq "9.11.9600.18059") { write-host $ie.ComputerName $ie.Data }
}
catch { write-host $computerName.Name not found }
}
错误:
Get-RegValue : Exception calling "OpenRemoteBaseKey" with "2" argument(s):
"The network path was not found.
"
At line:1 char:13
+ try { $ie = Get-RegValue -ComputerName $computerName.Name -Key
"Software\Microso ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorExcep
tion
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio
n,Get-RegValue
这是PSRemoteRegistry的一些限制吗?我做错了什么?
答案 0 :(得分:3)
这个Cmdlet真的很失败,并且在尝试连接之前没有检查机器是否可以访问。不是很好的行为。话虽这么说,要触发try / catch块,您必须为块中的cmdlet指定-ErrorAction。
将您的代码更改为此代码,它将有效。
foreach ($computerName in $computerNames) {
try {
$ie = Get-RegValue -ComputerName $computerName.Name -Key "Software\Microsoft\Internet Explorer" -Value Version -ErrorAction STOP
if ($ie.data -eq "9.11.9600.18059") { write-host $ie.ComputerName $ie.Data }
}
catch { write-host $computerName.Name not found }
}
指定ErrorAction会提示PowerShell查找用户定义的错误处理,并将调用您的try / catch块。否则,PowerShell依赖于cmdlet本身来处理错误。
进一步采取这一步,发出对象而不是纯文本。现在,您可以将其转储为Export-CSV或ConvertTo-HTML或任何其他cmdlet,并使结果与PowerShell中的内容相同。
foreach ($computerName in $computerNames) {
try {
$ie = Get-RegValue -ComputerName $computerName.Name -Key "Software\Microsoft\Internet Explorer" -Value Version -ErrorAction STOP
if ($ie.data -eq "9.11.9600.18059") {
[pscustomobject]@{ComputerName=$computerName.Name;IEVersion=$ie.Data}
}
}
catch {
[pscustomobject]@{ComputerName=$computerName.Name;IEVersion="Offline"}
}
}
输出
ComputerName IEVersion
------------ ---------
ham Offline
dellbook 9.11.10547.0