Powershell:使用try和catch进行错误处理

时间:2012-04-07 18:37:57

标签: powershell error-handling try-catch

我正在编写脚本并想控制错误。但是,我无法使用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 个答案:

答案 0 :(得分: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 *
}

对我没有意义。

您还可以捕获Generic Exception catch块中的错误,然后检查文本以查看它是否与您之后的单词匹配,但它有点脏。

答案 1 :(得分: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
  }
}