How to get the status of "Invoke-Expression", successful or unsuccessful?

Invoke-Expression will return all the text of the called command.

But how can I get the system's return value of whether this command was successful or failed? In CMD, I could use %errorlevel% to get the execution status of an external command. What about PowerShell?

+7
powershell exit-code
source share
2 answers

Usually should you use $? To check the status of the last statement executed:

 PS C:\> Write-Output 123 | Out-Null; $? True PS C:\> Non-ExistingCmdlet 123 | Out-Null; $? False 

However, this will not work with Invoke-Expression , because although the statement inside the expression passed to Invoke-Expression may fail, the Invoke-Expression it self call will be executed (i.e. the expression, although invalid / non-functional caused nonetheless)


With Invoke-Expression you have to use try:

 try { Invoke-Expression "Do-ErrorProneAction -Parameter $argument" } catch { # error handling go here, $_ contains the error record } 

or trap:

 trap { # error handling goes here, $_ contains the error record } Invoke-Expression "More-ErrorProneActions" 

An alternative is to add ";$?" to the expression you want to call:

 $Expr = "Write-Host $SomeValue" $Expr += ';$?' $Success = Invoke-Expression $Expr if(-not $Success){ # seems to have failed } 

but relies on no conveyor exit

+10
source share

In PowerShell, you can evaluate the status of execution by checking automatic variables

 $? Contains True if last operation succeeded and False otherwise. 

and / or

 $LASTEXITCODE Contains the exit code of the last Win32 executable execution. 

The former is used for PowerShell cmdlets, the latter for external commands (for example, %errorlevel% in batch scripts).

Does this help you?

+5
source share

All Articles