在powershell中,我可以使用Catch [System.UnauthorizedAccessException]捕获Access is Denied错误。我如何类似地捕获RPC服务器不可用错误?
答案 0 :(得分: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
答案 1 :(得分:2)
你可以捕捉到你想要的每一个例外。只需写下:
$_.Exception.GetType()
在你的捕获中,看看有什么异常,然后抓住它。