Powershell无法返回正确的退出代码 [英] Powershell fails to return proper exit code

查看:364
本文介绍了Powershell无法返回正确的退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When executing a Powershell script (in 2.0) using the -File command line switch, and explicitly defining the input parameters in Param, the exit code is always "0" (never fails) instead of properly returning the defined or expected error code.
This does not occur when using the explicit parameter definitions and the -Command switch, however for extraneous purposes, I need to keep the -File switch in my scripts.

任何有关解决方法的帮助(不涉及删除显式参数定义)将非常有帮助.

Any assistance with a workaround (that doesn't involve removing the explicit parameter definitions) would be extremely helpful.

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

Powershell "fails to return correct exit code":

exit1.ps1:显式定义参数的调用脚本.即使脚本的某些部分意外失败,错误级别也始终为0.

exit1.ps1: Call script that explicitly defines parameters. Errorlevel is always 0, even if there are parts of the script that ungraciously fail.

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函数以使其不那么明确时尝试做同样的事情:




Now, lets try the same thing when modifying the param function to be less explicit:

Exit1LooseParam.ps1:

Exit1LooseParam.ps1:

param(
    $arg1,
    $arg2,
    $arg3
);
exit 1;

输出(带有三个参数):

Output (with three parameters):

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

C:\temp\testnant>echo %errorlevel%
1




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




It appears that when you explicitly define the input parameters, Powershell seems to "lose its freakin mind" for some reason and fails to return the proper exit code.

有人有解决方法或能够解释为什么会发生这种情况吗?

Does anyone have a workaround or be able to explain why this is happening?

推荐答案

嗯,奇怪的是,我希望exit 1在这两种情况下都能工作.至少您可以同时使用两者:

Hmm that's odd, I'd expect exit 1 to work in both cases. At least you can use this for both:

[Environment]::Exit(1)

这篇关于Powershell无法返回正确的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆