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 {
An alternative is to add ";$?" to the expression you want to call:
$Expr = "Write-Host $SomeValue" $Expr += ';$?' $Success = Invoke-Expression $Expr if(-not $Success){
but relies on no conveyor exit
Mathias R. jessen
source share