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