在使用PowerShell 2.0时,如果在Param中显式定义输入参数并使用-File命令行开关来执行脚本,则退出代码始终为“0”(永远不会失败),而不是正确返回定义或预期的错误代码。但如果使用显式参数定义和-Command开关,则不会发生这种情况。但是,出于其他目的,我需要在我的脚本中保留-File开关。
请提供一个解决方法(不要涉及删除显式参数定义),这将非常有帮助。
PowerShell“无法返回正确的退出代码”:
exit1.ps1:调用显式定义参数的脚本。即使脚本中存在不友好的失败部分,错误级别始终为0。
请提供一个解决方法(不要涉及删除显式参数定义),这将非常有帮助。
PowerShell“无法返回正确的退出代码”:
exit1.ps1:调用显式定义参数的脚本。即使脚本中存在不友好的失败部分,错误级别始终为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似乎会"失去理智"并未能返回正确的退出代码。
是否有人有解决方法或能够解释为什么会发生这种情况?