3

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

2 回答 2

2

谁能弄清楚为什么我在尝试捕获 [System.Management.ManagementException] 类型的异常时无法捕获此异常?

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

IE:

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 块中捕获错误,然后检查文本以查看它是否与您之后的单词匹配,但它有点脏。

于 2012-04-08T23:25:27.397 回答
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
  }
}
于 2012-04-07T18:54:27.330 回答