How to get status of “Invoke-Expression”, successful or failed?

前端 未结 5 1210
故里飘歌
故里飘歌 2021-01-01 17:19

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 exec

5条回答
  •  情深已故
    2021-01-01 17:48

    $LASTEXITCODE cannot be used with Invoke-Expression, as it will be zero regardless of whether the expression invoked succeeds or fails:

    PS C:\Users\myUserAccount> touch temp.txt
    PS C:\Users\myUserAccount> Invoke-Expression "Remove-Item .\temp.txt"
    PS C:\Users\myUserAccount> echo $LASTEXITCODE
    0
    
    PS C:\Users\myUserAccount> Invoke-Expression "Remove-Item .\temp.txt"
    Remove-Item : Cannot find path 'C:\Users\myUserAccount\temp.txt' because it does not 
    exist.
    At line:1 char:1
    + Remove-Item .\temp.txt
    + ~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (C:\Users\myUserAccount\temp.txt:String) [Remove-Item], ItemNotFoundException
       + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
    
    PS C:\Users\myUserAccount> echo $LASTEXITCODE
    0
    

提交回复
热议问题