Invoke-Expression
will return all the text of the command being invoked.
But how can I get the system return value of whether this command has been executed successfully or with a failure? In CMD I could use %errorlevel%
to get external command execution state. What about PowerShell?
In PowerShell you can evaluate execution status by inspecting the automatic variables
and/or
The former is for PowerShell cmdlets, the latter for external commands (like
%errorlevel%
in batch scripts).Does this help you?
If the executable called by
Invoke-Expression
supports it, you can use$LASTEXITCODE
. You have to be careful about variable scoping, though.If you run it, the output will be:
Observe the 1 at the end denoting nonzero exit code.
If you would forget the
global:
prefix, instead the output would have 0. I believe this is because your function-scoped definition ofLASTEXITCODE
would hide the globally-set one.Normally you would use
$?
to inspect the status of the last statement executed:However, this won't work with
Invoke-Expression
, because even though a statement inside the expression passed toInvoke-Expression
may fail, theInvoke-Expression
call it self will have succeeded (ie. the expression, although invalid/non-functional was invoked none the less)With
Invoke-Expression
you'll have to use try:or a trap:
The alternative is the append
";$?"
to the expression you want to invoke:but relies on there not being any pipeline output
$LASTEXITCODE cannot be used with Invoke-Expression, as it will be zero regardless of whether the expression invoked succeeds or fails: