【问题标题】:Powershell: error handling with try and catchPowershell:使用 try 和 catch 进行错误处理
【发布时间】:2012-04-20 21:11:06
【问题描述】:

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

【问题讨论】:

    标签: powershell error-handling try-catch


    【解决方案1】:

    谁能弄清楚为什么我在尝试捕获 [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 块中捕获错误,然后检查文本以查看它是否与您要查找的单词匹配,但它有点脏。

    【讨论】:

      【解决方案2】:

      您必须使用-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
        }
      }
      

      【讨论】:

      • 感谢您的快速回复。特别是如何捕获错误消息“用户凭据不能用于本地连接”?其他错误希望使用不同的代码进行处理。谢谢
      • 你是对的:“用户凭据不能用于本地连接”
      猜你喜欢
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      相关资源
      最近更新 更多