Benutzer:MovGP0/Powershell/Exception Handling

aus Wikipedia, der freien Enzyklopädie
< Benutzer:MovGP0‎ | Powershell
Dies ist die aktuelle Version dieser Seite, zuletzt bearbeitet am 8. September 2016 um 11:20 Uhr durch imported>MovGP0(77247) (→‎Exception Handling).
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Exception Handling

try {
    # ...
} catch {
    Write-Exception $_
    throw;
} finally {
    # ...
}
function Write-Exception {
  param(
    [Parameter(Mandatory=$true, Position=0)]
    $thisError
  )
  process{
    [System.Text.StringBuilder]$builder = New-Object -TypeName "System.Text.StringBuilder"; 
    $builder.AppendLine($thisError.Exception);
    $builder.AppendLine($thisError.Exception.StackTrace);
    $builder.AppendLine("at line $($thisError.InvocationInfo.ScriptLineNumber) char $($thisError.InvocationInfo.OffsetInLine)");
    $builder.AppendLine($thisError.InvocationInfo.Line);
    $builder.AppendLine($thisError.InvocationInfo.ScriptName);
    Write-Error $builder.ToString();
  }
}

Error Trapping

function Do-Something {
    param(
        [Parameter()]
        [string]$foo
    )
    trap [Exception] {
        Write-Exception $_
        Continue # Break
    }
    begin {
    }
    process {
        # ...
    }
    end {
    }
}