首页 > 解决方案 > PowerShell > 为什么我需要在函数返回值之前内联声明函数参数?

问题描述

我的代码抛出 FileNotFoundException 并将错误消息打印到控制台。


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
}

在 catch 块中,我调用了一个返回异常消息的函数。仅当函数参数也在函数中内联声明时,该函数才返回值。否则我得到一个空的结果。

在此处输入图像描述

Get-ErrorMessage 的返回值为空或正确的错误消息,具体取决于第 18 行。

如果将此行添加到代码中,我会按预期返回错误消息

$Ex

在此处输入图像描述

如果我将其注释掉,则不会返回任何内容

#$Ex

在此处输入图像描述

我不确定这里发生了什么。任何想法

在此处输入图像描述

标签: powershell

解决方案


$_您的变量$Ex不是类型System.Exception或继承自它,因此没有属性Message并且将始终返回$null

这两个变量是 type System.Management.Automation.ErrorRecord。您必须使用$Ex.Exception.Message$Ex.Exception.InnerException获得所需的输出。

以下是您的 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]

推荐阅读