假設我cd到 powershell 中的一個空目錄并運行以下命令:
get-childitem x
該命令將拋出找不到路徑的錯誤,這是預期的。
但是,當我檢查$LastExitCode它時它仍然為零。
這讓我感到困惑,因為根據檔案$LastExitCode應該包含最后運行的基于 Windows 的程式的退出代碼。
任何人都可以解釋為什么在我運行一個明顯失敗的命令后退出代碼仍然為零?
uj5u.com熱心網友回復:
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:\>
uj5u.com熱心網友回復:
在 powershell 腳本中,您可以在底部執行以下操作:
exit $error.count
然后退出代碼將是錯誤的數量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401120.html
標籤:电源外壳
上一篇:ImageDataGenerator(Keras)中的channel_shift_range和brightness_range的區別?
