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 ブロックではキャッチされません!

すなわち:

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/catchまたはスクリプトブロックに使用する必要がありますtrap。これをテストできます:

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 に答える