2016-05-15 17 views
0

列挙値のErrorRecord.CategoryInfo.Categoryに基づいてエラーを処理しようとしています。PowerShellのErrorRecord.CategoryInfo.Categoryをテストします。

コード:コードではなくdefaultスイッチで、ErrorCategory.InvalidTypeスイッチを実行していないのはなぜ

try { 
    # assembly not installed on workstation 
    [Reflection.Assembly]::LoadWithPartialName('Oracle.DataAccess') 
    # throws error with a category of 'InvalidType' 
    $connection = New-Object Oracle.DataAccess.Client.OracleConnection($ConnectionString) 
    $Connection.Open() 

} 
catch { 
    # generates 'DEBUG: CategoryInfo.Category: InvalidType' 
    write-debug "CategoryInfo.Category: $($_.CategoryInfo.Category)" 

    # generates 'DEBUG: Category: InvalidType' (the `default` switch) 
    switch ($_.CategoryInfo.Category) { 
     [ErrorCategory.InvalidType] {Write-Debug "InvalidType"} 
     [ErrorCategory.InvalidOperation] {Write-Debug "InvalidOperation"} 
     default { write-Debug "Category: $($_.CategoryInfo.Category)" } 
    } 
} 

Referencing system.management.automation.dll in Visual Studioに受け入れられる回答は、system.management.automationアセンブリをインストールする必要があることを示唆しています。

このアセンブリをインストールしなくても$_.CategoryInfo.Categoryをテストする方法はありますか?

+0

リンクされた質問がどのように関連しているかわかりません。 'System.Management.Automation.dll'はPowerShellの中核です。 PowerShellをC#/ VbScriptで使用するには、参照する必要があります。 –

答えて

3

[ErrorCategory.InvalidType]はenumを使用するPowerShellの構文ではないため動作しません。

enum-value(name)を直接指定してPowerShellに変換させるか、enumに直接アクセスできるようにすることができます。例:

switch ($_.CategoryInfo.Category) { 
    InvalidType {Write-Debug "InvalidType"} 
    ([System.Management.Automation.ErrorCategory]::InvalidOperation) {Write-Debug "InvalidOperation"} 
    default { write-Debug "Category: $($_.CategoryInfo.Category)" } 
} 
関連する問題