问题
In powershell, I can catch Access is Denied error using Catch [System.UnauthorizedAccessException]. How do I similarly catch RPC Server Unavailable error?
回答1:
If you add the common parameter -ErrorAction Stop to the, in my case, get-wmiobject command it will cause the command to respond to this non-terminating error as a terminating error and drop it to catch for action.
Here is the code I'm using for this purpose. I probably should be more specific in the catch, but it works for now.
# 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
回答2:
You can catch every exception you want. Just write:
$_.Exception.GetType()
inside your catch to see what exception is there and then catch it.
来源:https://stackoverflow.com/questions/8086357/catch-rpc-server-unavailable-error-hresult-0x800706ba