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

Jon*_*nyG 12 parameters powershell exit-code parameter-passing errorlevel

当使用-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;
Run Code Online (Sandbox Code Playgroud)

输出:

C:\temp\testnant>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\exit1.ps1 "one" "two" "three"

C:\temp\testnant>echo %errorlevel%
0
Run Code Online (Sandbox Code Playgroud)




现在,让我们在将param函数修改为不那么明确时尝试相同的事情:

Exit1LooseParam.ps1:

param(
    $arg1,
    $arg2,
    $arg3
);
exit 1;
Run Code Online (Sandbox Code Playgroud)

输出(带三个参数):

C:\temp\testnant>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\Exit1looseParam.ps1 "one" "two" "three"

C:\temp\testnant>echo %errorlevel%
1
Run Code Online (Sandbox Code Playgroud)




看来,当你明确定义输入参数时,Powershell由于某种原因似乎"失去了它的思维"并且无法返回正确的退出代码.

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

And*_*ndi 14

嗯,这很奇怪,我希望exit 1在这两种情况下工作.至少你可以用它们:

[Environment]::Exit(1)