Home > Back-end >  Exit code in powershell still zero even though cmdlet throws an error
Exit code in powershell still zero even though cmdlet throws an error

Time:01-02

Suppose I cd to an empty directory in powershell and run the following command:

get-childitem x

The command will throw an error that it cannot find the path, which is expected.

However, when I check the $LastExitCode it is still zero.

This is confusing to me, since according to the docs $LastExitCode should contain the exit code of the last windows-based program that was run.

Could anyone please explain why the exit code is still zero after I run a command which clearly fails?

CodePudding user response:

get-childitem doesn't start a new process. If a powershell function or command throws an error it will be stored in the global $Error array. $LASTEXITCODE is created and set when you start a child process, for example a new powershell session with a command:

PS C:\> Get-ChildItem x
Get-ChildItem : Cannot find path 'C:\x' because it does not exist.
At line:1 char:1
  Get-ChildItem x
  ~~~~~~~~~~~~~~~
      CategoryInfo          : ObjectNotFound: (C:\x:String) [Get-ChildItem], ItemNotFoundException
      FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

PS C:\> $Error.Count
1
PS C:\> $Error[0]
Get-ChildItem : Cannot find path 'C:\x' because it does not exist.
At line:1 char:1
  Get-ChildItem x
  ~~~~~~~~~~~~~~~
      CategoryInfo          : ObjectNotFound: (C:\x:String) [Get-ChildItem], ItemNotFoundException
      FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

PS C:\> $LASTEXITCODE
PS C:\> powershell -Command { get-childitem x }
get-childitem : Cannot find path 'C:\x' because it does not exist.
At line:1 char:2
   get-childitem x
   ~~~~~~~~~~~~~~~
      CategoryInfo          : ObjectNotFound: (C:\x:String) [Get-ChildItem], ItemNotFoundException
      FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

PS C:\> $LASTEXITCODE
1
PS C:\> powershell -Command { get-childitem . }


    Directory: C:\


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
.....
.....
.....


PS C:\> $LASTEXITCODE
0
PS C:\>

CodePudding user response:

In a powershell script you can do something like this at the bottom:

exit $error.count

Then the exit code will be the number of errors.

  • Related