12
當使用命令行開關執行Powershell腳本(2.0版)並在Param中顯式定義輸入參數時,退出代碼始終爲「0」(永不失敗)而不是正確地返回已定義或預期的錯誤代碼。
當使用顯式參數定義和命令開關時,不會發生這種情況,但是出於無關的目的,我需要將-File開關保留在腳本中。Powershell無法返回正確的退出代碼
對解決方法(不包括刪除顯式參數定義)的任何幫助將非常有幫助。
Powershell的 「不能返回正確的退出代碼」:
exit1.ps1:調用腳本明確定義的參數。 Errorlevel始終爲0,即使腳本的某些部分無故失敗。
param(
[Parameter(mandatory=$true)][string]$arg1,
[Parameter(mandatory=$true)][string]$arg2,
[Parameter(mandatory=$true)][string]$arg3
);
exit 1;
輸出:
C:\temp\testnant>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\exit1.ps1 "one" "two" "three"
C:\temp\testnant>echo %errorlevel%
0
現在,讓我們嘗試同樣的事情,改變帕拉姆功能時要少明確:
Exit1LooseParam.ps1:
param(
$arg1,
$arg2,
$arg3
);
exit 1;
輸出(帶有三個參數):
C:\temp\testnant>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\Exit1looseParam.ps1 "one" "two" "three"
C:\temp\testnant>echo %errorlevel%
1
看來,當你明確地定義輸入參數,PowerShell的似乎「失去刻着記」出於某種原因而未能返回正確的退出碼。
有沒有人有一種變通方法或可以解釋爲什麼發生這種情況?
這似乎正確地返回退出代碼。謝謝! – JonnyG 2012-01-18 17:44:41
謝謝你,只是爲我解決了一個問題:) – 2012-08-31 14:46:45
沒有這個我只能得到出口返回0或1 – cmcginty 2014-05-20 00:41:40