ErrorVariable不使用null或空参数

时间:2014-06-27 21:19:29

标签: powershell error-handling

如果参数为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上测试过它,但仍看到相同的结果。

1 个答案:

答案 0 :(得分:4)

错误没有显示在错误变量中,因为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