Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit code in powershell still zero even though cmdlet throws an error

Tags:

powershell

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?

like image 450
user32882 Avatar asked Jul 27 '26 05:07

user32882


1 Answers

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:\>
like image 149
mcbr Avatar answered Jul 28 '26 20:07

mcbr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!