使用以下命令执行 Powershell 脚本(2.0 中)时-File命令行开关,并在 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;
Output:
C:\temp\testnant>powershell -noprofile -nologo -noninteractive -executionpolicy Bypass -file .\exit1.ps1 "one" "two" "three"
C:\temp\testnant>echo %errorlevel%
0
现在,让我们在修改 param 函数以使其不那么明确时尝试同样的操作:
退出1LooseParam.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 似乎由于某种原因“失去了理智”,并且无法返回正确的退出代码。
有谁有解决方法或能够解释为什么会发生这种情况?