时间:2014-10-04 16:11:10

标签: powershell try-catch




#Make sure the system is actually on before we try to access the registry and wait for timeout or error
if (Test-Connection $Device.IPAddresses -Count 1 -ErrorAction SilentlyContinue)
    Try { # test the registry connection, this will likely fail on workgroup systems
        if (Get-RemoteRegistryKey -RegKeyPath $RegKeyPath -RegValueName $RegValueName -ComputerName $Device.DNSname)
            $SusClientID = $null # blank out the susclientid var so we don't unintentionally recycle it and put out bad data, because purple
            # now query the registry and put it into a var so we can fookin do stuff
            $SusClientID = Get-RemoteRegistryKey -RegKeyPath $RegKeyPath -RegValueName $RegValueName -ComputerName $Device.DNSname
        else {Write-Output $Device.DNSname " is offline"}
        } # now catch errors, likely caused by credential issues or bad dns resolution
    Catch [UnauthorizedAccessException] {Write-Output ($Device.DNSname + " cannot access remote registry")
    Finally { # finally lets compare the sysclient id on the machine to that in the database
        if ($SusClientID) # -match "\A[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\z")
            if ((Compare-Object $SusClientID $Device.SusClientId) -eq $null)
                {Write-Output ($Device.DNSname +" SusClientId matches database.")}
            elseif ($SusClientID -eq $null -or $SusClientID -eq "") {} # this didn't work as I'd hoped
            else {
                # notmatching a SusClientId GUID will not catch systems with malformed ID's, commenting this out until a better method is found
                #if ($SusClientID -notmatch "\A[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\z")
                Write-Output ($Device.DNSname +" SusClientId does not match.")}



pc-001.sergeinc.org cannot access remote registry
pc-001.sergeinc.org SusClientId does not match.
pc-002.sergeinc.org SusClientId matches database.
pc-003.sergeinc.org SusClientId matches database.
srv-ad.sergeinc.org SusClientId matches database.
pc-xptest-001.sergeinc.org SusClientId matches database.
pc-004.sergeinc.org is offline
pc-005.sergeinc.org SusClientId does not match.

1 个答案:

答案 0 :(得分:0)

这可能是个人偏好,但我尝试在任何try {...}块中根据需要添加尽可能少的命令。我也不确定它是否值得拥有finally {...}块。在这种情况下,一旦您知道设备与Test-Connection语句联机,我就会这样做:

$SusClientID = $null

try {
  $SusClientID = Get-RemoteRegistryKey -RegKeyPath $RegKeyPath -RegValueName $RegValueName -ComputerName $Device.DNSname
catch {

if($SusClientID) {
} else {

这可以更清楚地说明哪个语句为catch {...}块生成错误。

请注意,如果您循环浏览设备列表,那么在每个循环开始时将 $ SusClientID 设置为 $ null 肯定是有效的,或者如果发现错误,也可以将其明确设置为 $ null