即使cmdlet抛出错误,powershell中的退出代码仍然为零



假设我cd到powershell中的一个空目录,并运行以下命令:

get-childitem x

该命令将抛出一个错误,即无法找到预期的路径。

然而,当我检查$LastExitCode时,它仍然为零。

这让我很困惑,因为根据文档,$LastExitCode应该包含上次运行的基于windows的程序的退出代码。

有人能解释一下为什么在我运行了一个明显失败的命令后,退出代码仍然为零吗?

get-childitem不会启动新流程。如果powershell函数或命令抛出错误,它将存储在全局$Error数组中。$LASTEXITCODE是在启动子进程时创建和设置的,例如使用以下命令的新powershell会话:

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:>

在powershell脚本中,您可以在底部执行以下操作:

exit $error.count

那么退出代码将是错误的数量。

相关内容

最新更新