13

使用-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 似乎出于某种原因“失去了它的疯狂思维”并且无法返回正确的退出代码。

有没有人有解决方法或能够解释为什么会这样?

4

1 回答 1

15

嗯,这很奇怪,我希望exit 1在这两种情况下都能工作。至少您可以将其用于两者:

[Environment]::Exit(1)

于 2012-01-17T21:59:54.397 回答