Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Last active March 7, 2018 19:19
Show Gist options
  • Save Jaykul/98ec20a655c028af95efe4d473e4ea26 to your computer and use it in GitHub Desktop.
Save Jaykul/98ec20a655c028af95efe4d473e4ea26 to your computer and use it in GitHub Desktop.
Try this example, then try changing line 14 to catch [exception]
using namespace System.Management.Automation
& {
[CmdletBinding()]param()
$ErrorActionPreference = "Stop"
try { # Standard practice in every script
Get-Item NoSuchFile
} catch [ItemNotFoundException] {
Write-Warning "File not found, using workaround ... "
<# do stuff to work around that #>
} catch { # Standard practice in every script
$ex = $_
do {
$Stack = if($ex.ScriptStackTrace) { $ex.ScriptStackTrace } else { $ex.StackTrace }
$PSCmdlet.WriteInformation(@(
$ex.GetType().Fullname
"Stack Trace:"
($Stack | Out-String -width 100) -split "`n" -replace "^\s*"," "
) -join "`n", ("PSHOST", "Exception"))
} while($ex = if($ex.Exception) { $ex.Exception } else { $ex.InnerException })
throw
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment