Tony
Tony

Reputation: 1694

PowerShell > Why do I need to declare the function parameter inline in the function before it returns a value?

My code throws an FileNotFoundException and prints the error message to the console.


try {        
    throw [System.IO.FileNotFoundException] "file not found."        
}
catch [System.IO.FileNotFoundException] {
    
    $msg = Get-ErrorMessage -ex $_
    Write-Host "Exception message: $($msg)"
}

function Get-ErrorMessage() {
    Param(

        [Parameter(Mandatory = $True)]
        [System.Management.Automation.ErrorRecord]
        $Ex
    )   
    $Ex
    $errorMessage = $Ex.Message
    
    if ($null -ne $Ex.innerExecption) {
        $errorMessage = $Ex.InnerException.Message
    } 

    return $errorMessage
}

In the catch block I call a function that returns the exception message. The function only returns value if the function parameters also are being declared inline in the function. Otherwise I get an empty result.

enter image description here

The return value from Get-ErrorMessage is either empty or the correct error message depending on line 18.

If this line is added to the code I get the error message back as expected

$Ex

enter image description here

If I comment it out, nothing is returned

#$Ex

enter image description here

I am not sure what is going on here. Any idea

enter image description here

Upvotes: 1

Views: 130

Answers (1)

swbbl
swbbl

Reputation: 864

Your variables $_ and $Ex is not of type System.Exception or does inherit from it, hence has no property Message and will always return $null

Those two variable are of type System.Management.Automation.ErrorRecord. You have to use $Ex.Exception.Message and $Ex.Exception.InnerException to get the required output.

Here's an overview (depth: two levels) of the properties of your ErrorRecord:

[ErrorRecord] file not found.
        PSMessageDetails                             : [Object]
        Exception                                    : [FileNotFoundException] System.IO.FileNotFoundException: file not found.
                Message                                      : [String] file not found.
                FileName                                     : [String]
                FusionLog                                    : [String]
                Data                                         : {[ListDictionaryInternal]} ~
                InnerException                               : [Exception]
                TargetSite                                   : [MethodBase]
                StackTrace                                   : [String]
                HelpLink                                     : [String]
                Source                                       : [String]
                HResult                                      : [Int32] -2147024894
        TargetObject                                 : [Object]
        CategoryInfo                                 : [ErrorCategoryInfo] OperationStopped: (:) [], FileNotFoundException
                Category                                     : {[ErrorCategory]} OperationStopped
                Activity                                     : [String] 
                Reason                                       : [String] FileNotFoundException
                TargetName                                   : [String] 
                TargetType                                   : [String] 
        FullyQualifiedErrorId                        : [String] file not found.
        ErrorDetails                                 : [ErrorDetails]
        InvocationInfo                               : [InvocationInfo] ~System.Management.Automation.InvocationInfo
                MyCommand                                    : [CommandInfo]
                BoundParameters                              : {[Dictionary`2]} ~
                UnboundArguments                             : {@[List`1]} ~System.Collections.Generic.List`1[System.Object]
                ScriptLineNumber                             : [Int32] 25
                OffsetInLine                                 : [Int32] 2
                HistoryId                                    : [Int64] -1
                ScriptName                                   : [String] 
                Line                                         : [String]         throw [System.IO.FileNotFoundException] 'file not found.'        

                PositionMessage                              : [String] At line:25 char:2
                                                                       +     throw [System.IO.FileNotFoundException] 'file not found.'
                                                                       +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                PSScriptRoot                                 : [String] 
                PSCommandPath                                : [String]
                InvocationName                               : [String] 
                PipelineLength                               : [Int32] 0
                PipelinePosition                             : [Int32] 0
                ExpectingInput                               : [Boolean] False
                CommandOrigin                                : {[CommandOrigin]} Internal
                DisplayScriptPosition                        : [IScriptExtent]
        ScriptStackTrace                             : [String] at <ScriptBlock>, <No file>: line 25
        PipelineIterationInfo                        : @[ReadOnlyCollection`1]

Upvotes: 1

Related Questions