如果参数为null或为空,则-ErrorVariable
捕获错误时会出现问题。这是一个例子:
PS> Get-Process $svc
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
374 14 5180 4996 49 596 svchost
PS> get-process $noProcess -ErrorVariable MyErr
Get-Process : Cannot validate argument on parameter 'Name'. The argument is
null or empty. Supply an argument that is not null or empty and then try the
command again.
At line:1 char:13
+ get-process $noProcess -ErrorVariable MyErr
+ ~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Process], ParameterBinding
ValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power
Shell.Commands.GetProcessCommand
PS> $MyErr # <----ErrorVariable did not capture error
PS> $Error[0]
Get-Process : Cannot validate argument on parameter 'Name'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
关于为什么
-ErrorVariable
在这种情况下不起作用的任何想法?我已经在其他cmdlet和PowerShell 3.0/4.0上对其进行了测试,但仍然看到相同的结果。 最佳答案
该错误未显示在error变量中,因为Get-Process并未引发该错误。它由命令处理器抛出,试图验证参数,以便可以运行Get-Process。 Get-Process永远不需要运行,因此它永远没有机会将任何内容放入变量中。
可能的解决方法:
try{
Get-Process $noprocess -ErrorVariable MyErr
}
Catch { $MyErr = $Error[0] }
$MyErr
Get-Process : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
At line:3 char:17
+ Get-Process $noprocess -ErrorVariable MyErr
+ ~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetProcessCommand
关于powershell - ErrorVariable无法使用null或空参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24460906/