Powershell尝试抓住继续

时间:2013-11-12 21:05:40

标签: loops powershell try-catch

我有一个有效的PowerShell脚本,但是当它找不到主机名时,它会抛出一个非终止异常并写入无法找到该主机名的屏幕。我想捕获该异常,只需写入屏幕:Not Found。然后我希望脚本继续正常进行。

这是脚本:

$listOfComputers = IMPORT-CSV test.txt
$b = "2013-09-11"
ForEach($computer in $listOfComputers){
$name = $computer.Name
Write-Host $name -NoNewLine
try{$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $name)}
catch [Exception] {write-host "  Not Found" -foreground blue}
$key = $reg.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\Results\\Install")
$a = $key.GetValue("LastSuccessTime")
$a = $a.Substring(0,10)
if($a -le $b){Write-Host " " $a -foreground magenta}
else{Write-Host " " $a} 
}

这是输出:

PS C:\PowerShell Scripts> .\windowsUpdates.ps1
OLDBEAR  Not Found
You cannot call a method on a null-valued expression.
At C:\PowerShell Scripts\windowsUpdates.ps1:8 char:1
+ $key =
$reg.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpd
     

...       + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~       ~~~           + CategoryInfo:InvalidOperation:(:) [],RuntimeException           + FullyQualifiedErrorId:InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\PowerShell Scripts\windowsUpdates.ps1:9 char:1
+ $a = $key.GetValue("LastSuccessTime")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\PowerShell Scripts\windowsUpdates.ps1:10 char:1
+ $a = $a.Substring(0,10)
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

完全跳过try / catch,然后在尝试访问注册表之前测试连接。这样可以加快您的脚本速度,因为您不会等待OpenRemoteBaseKey在脱机系统上的超时。

$listOfComputers = IMPORT-CSV test.txt
$b = "2013-09-11"
ForEach($computer in $listOfComputers){
    $name = $computer.Name
    Write-Host $name -NoNewLine
    if (-not (Test-Connection -computername $name -count 1 -Quiet -ErrorAction SilentlyContinue) {
        write-host "  Not Found" -foreground blue;
        continue;
    }
    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $name)

    $key = $reg.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\Results\\Install")
    $a = $key.GetValue("LastSuccessTime")
    $a = $a.Substring(0,10)
    if($a -le $b) {
        Write-Host " " $a -foreground magenta
    }
    else {
        Write-Host " " $a;
    } 
}

您还可以在点击主循环之前批量测试连接,过滤列表中无法访问的所有计算机。请参阅我的回答over here了解相关方法。