Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

$_.Exception is $null when used in a call – why?

I have a PowerShell script containing the following logging function:

function LogError([string] $message, $exception = $null) {…}

In a try-catch block, when an exception occurs, I call that logging function like this:

catch { LogError("…", $_.Exception) }

In the LogError function, the second argument is always $null. Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I couldn’t find any documentation that would explain why I cannot use $_.Exception in a function call or that I am supposed to use instead.

>Solution :

Powershell function arguments are not passed using the parenthesis / comma formatting.

That is bad

LogError("…", $_.Exception)

Powershell take that as a single array argument.
This is actually the same as LogError -Message ("...",$_.Exception)

That is ok

LogError '…' $_.Exception

That is best

 LogError -message '...' -exception $_.Exception

Complete working example

function LogError([string] $message, $exception = $null) {
  Write-Host $message
   $exception | Out-String | Write-Host -ForegroundColor red 
  }

try {
  throw 'Noooo !!!!'
}
catch {
  LogError -message 'oops' -exception $_.Exception
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading