$_您的变量$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]