powershellpowershell-7.0powershell-7.2

$_.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?

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
    }