2012-04-07 30 views
2

我正在编写脚本并希望控制错误。然而,即时通讯使用try,catch发现错误处理的信息很麻烦。我想捕获特定的错误(如下所示),然后执行一些操作并恢复代码。这需要什么代码?Powershell:使用try和catch进行错误处理

这是我正在运行的代码,即时提示输入无效的用户名。

Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential) 



Get-WmiObject : User credentials cannot be used for local connections 
At C:\Users\alex.kelly\AppData\Local\Temp\a3f819b4-4321-4743-acb5-0183dff88462.ps1:2 char:16 
+   Get-WMIObject <<<< Win32_Service -ComputerName localhost -Credential (Get-Credential) 
    + CategoryInfo   : InvalidOperation: (:) [Get-WmiObject], ManagementException 
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand 

回答

2

谁能弄清楚为什么我不能捕获该异常试图类型[System.Management.ManagementException]的异常陷阱是什么时候?

PowerShell应该能够捕获与某些异常类匹配的异常,但即使下面的异常类是[System.Management.ManagementException],它也不会捕获该catch块中的异常!

即:

Try 
{ 
    Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential) -ErrorAction "Stop" 
} 
Catch [System.Management.ManagementException] 
{ 
    Write-Host "System.Management.ManagementException" 
    Write-Host $_ 
    $_ | Select * 
} 
Catch [Exception] 
{ 
    Write-Host "Generic Exception" 
    Write-Host $_ 
    $_ | Select * 
} 

的工作方式相同:

Try 
{ 
    Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential) -ErrorAction "Stop" 
} 
Catch [Exception] 
{ 
    Write-Host "Generic Exception" 
    Write-Host $_ 
    $_ | Select * 
} 

没有道理给我。

您也可以捕获通用异常捕获块中的错误,然后检查文本以查看它是否与您之后的文字相匹配,但是有点脏。

1

必须使用-erroraction stop进入the try/catchtrap脚本块。您可以测试此:

Clear-Host 
$blGoOn = $true 

while ($blGoOn) 
{ 
    trap 
    { 
    Write-Host $_.exception.message 
    continue 
    } 
    Get-WMIObject Win32_Service -ComputerName $computer -Credential (Get-Credential) -ErrorAction Stop 
    if ($?) 
    { 
    $blGoOn=$false 
    } 
} 
+0

感谢您的迅速回复。如何捕获错误消息“用户凭证不能用于本地连接”?其他错误想要用不同的代码处理。谢谢 – resolver101 2012-04-08 09:52:18

+0

你是对的:“用户凭证不能用于本地连接” – JPBlanc 2012-04-08 14:40:37

相关问题