【发布时间】:2012-02-12 16:37:08
【问题描述】:
当使用 -File 命令行开关执行 Powershell 脚本(在 2.0 中)并在 Param 中显式定义输入参数时,退出代码始终为“0”(从不失败)而不是正确返回定义或预期的错误代码。
使用显式参数定义和 -Command 开关时不会发生这种情况,但是出于无关目的,我需要在脚本中保留 -File 开关。
解决方法(不涉及删除显式参数定义)的任何帮助都将非常有帮助。
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
现在,让我们在将 param 函数修改为不那么明确时尝试同样的事情:
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 似乎出于某种原因“失去了它的疯狂思维”并且无法返回正确的退出代码。
有没有人有解决方法或能够解释为什么会发生这种情况?
【问题讨论】:
标签: powershell parameters parameter-passing exit-code errorlevel