PowerShell – Various Annoyances

Terminating errors vs. Non-terminating errors.
This will “fail” (a.k.a. worked as designed) and skip over the catch block because it is a non-terminating error.

try
{
Import-Module BogusModule
}
catch
{
Write-Warning "BogusModule could not be loaded."
Write-Output $Error[0]
}

This will work:

try
{
Import-Module BogusModule -ErrorAction 'Stop'
}
catch
{
Write-Warning "BogusModule could not be loaded."
Write-Output $Error[0]
}

Reference function:
http://stackoverflow.com/questions/10498433/how-to-correctly-ignore-import-module-errors-in-powershell

Annoyance:
PowerShell deciding how it will format (“rolling” and “unrolling” objects) an item on output.
An intermediary function for CSV as an example:

Avoiding System.Object[] (or Similar Output) when using Export-Csv

Leave a comment