1

I am having issues with -ErrorVariable capturing an error if the argument is null or empty. Here is an example:

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.

Any thoughts as to why -ErrorVariable would not work in this case? I have tested it on other cmdlets and PowerShell 3.0/4.0 and still see the same results.

1 Answer 1

4

The error didn't show up in the error variable because the error wasn't thrown by Get-Process. It was thrown by the command processor trying to validate the parameters so it could run Get-Process. Get-Process never got to run, so it never had a chance to put anything into the variable.

Possible workaround:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explaining it. It was driving me crazy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.