首页 文章

Powershell无法返回正确的退出代码

提问于
浏览
12

使用 -File 命令行开关执行Powershell脚本(在2.0中)并在Param中显式定义输入参数时,退出代码始终为"0"(永不失败),而不是正确返回已定义或预期的错误代码 .
使用显式参数定义和 -Command 开关时不会发生这种情况,但是出于无关的目的,我需要在脚本中保留-File开关 .

使用 workaround (不涉及删除显式参数定义)的任何帮助都将非常有用 .

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似乎是"lose its freakin mind"并且无法返回正确的退出代码 .

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

1 回答

  • 14

    嗯,'s odd, I'期望 exit 1 在这两种情况下都能工作 . 至少你可以用它们:

    [Environment]::Exit(1)

相关问题