2011-11-10 50 views
2

在PowerShell中,我可以使用Catch [System.UnauthorizedAccessException]捕獲Access is Denied錯誤。我該如何捕獲RPC Server Unavailable錯誤?捕獲RPC服務器不可用錯誤HRESULT:0x800706BA

+0

我覺得這是更細節的錯誤: '獲取-WmiObject可以:RPC服務器不可用。 (來自HRESULT的異常:0x800706BA) 在C:\ Users \ flickerfly \ Documents \ scripts \ Set-LocalServerAdmin.ps1:22 char:33 + $ oldexists = Get-WmiObject <<<< Win32_UserAccount -Filter「Name ='$ olduser'「-C計算機名$ computerName + CategoryInfo:InvalidOperation:(:) [Get-WmiObject],COMException + FullyQualifiedErrorId:GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand' – flickerfly

回答

2

你可以捕捉到你想要的每個異常。只需寫:

$_.Exception.GetType() 

在你的catch裏面看看有什麼異常,然後抓住它。

+0

這是一個非終止錯誤。 – flickerfly

4

如果您將通用參數-ErrorAction Stop添加到(在我的情況中爲get-wmiobject命令),它將導致命令將此非終止錯誤作爲終止錯誤作出響應,並將其放回執行狀態。

這是我用於此目的的代碼。我可能應該更具體的抓住,但它現在工作。

# Is this machine on network?, if not, move to next machine 
If (!(Test-Connection -ComputerName $computerName -Count 1 -Quiet)) { 
    Write-Host "$computerName not on network." 
    Continue # Move to next computer 
} 

# Does the local Administrator account exist? Returns a string if it exists, which is true-ish. 
try { 

    $filter = "Name='$olduser' AND Domain='$computerName'" 
    $account = Get-WmiObject Win32_UserAccount -Filter $filter -ComputerName $computerName -ErrorAction Stop 

} catch { 

    Write-Warning "$computerName Can't check for accounts, likely RPC server unavailable" 
    Continue # Move to next computer 

} #end try 
+0

你在$ olduser變量中寫什麼? Loacl管理員用戶名? – Bomberlt

+0

這是我的一部分腳本正在更改管理員帳戶的用戶名我相信。 $ olduser是我更改爲另一個用戶名的用戶帳戶的名稱。所以$ olduser可能會是「管理員」。 $賬戶將成爲「管理員」賬戶對象(如果存在的話)。如果不是,那麼它將不包括用戶對象,並且顯然不需要任何關注。 (已經過了一段時間,但我認爲這就是它的工作原理。) – flickerfly

+1

看起來RPC服務器不可用錯誤沒有被默認捕獲,因此OP的問題可能(或者,* my *問題:)但是添加-ErrorAction Stop to我的GWMI能做到這一點,謝謝。 – Shoeless

相關問題