Powershell - 将 Powershell 退出代码 ($LASTEXITCODE) 返回到 CommandLine (%errorlevel%)

问题描述 投票:0回答:2

我有一个名为

exit_three.ps1
的 powershell 脚本,它什么都不做
exit 3
。 如果我从 powershell 调用这个脚本,我可以通过
$LASTEXITCODE

得到它的返回值

但是现在,我想从 CMD 调用这个脚本并将它的返回值(即

3
)传递给 cmd-own
%errorlevel%
- 变量。

我读了很多答案,但似乎没有一个对我来说容易使用/工作。

powershell cmd return
2个回答
1
投票

%ERRORLEVEL%
环境变量包含当前
ERRORLEVEL
值,程序退出时自动设置.

powershell.exe -noprofile -c "& {D:\PShell\SO\exit_three.ps1}"
echo %errorlevel%
0

不足为奇,因为

powershell.exe
默认退出代码是
0

使用任一个

powershell -noprofile -c "& {D:\PShell\SO\exit_three.ps1;exit $LASTEXITCODE}"
echo %errorlevel%
3

1

(call )
powershell -noprofile -file D:\PShell\SO\exit_three.ps1
echo %errorlevel%
3

1 请注意

(call )
在这里设置
ERRORLEVEL
0
(仅用于调试目的):
Dave Benham 回复 setting ERRORLEVEL to 0 问题: *如果你想将
errorlevel
强制转换为
0
,那么你可以使用这个完全不直观但非常有效的语法:
(call )
call 之后的空格很关键。如果要将errorlevel设置为1,可以使用
(call)
。关键是call后没有空格。


0
投票

使用标志 -file 执行 Powershell 脚本。

以下脚本“test.ps1”

1
2
3
exit 4

使用:

C:\>powershell -file test.ps1

输出:

1
2
3

使用:

C:\>echo %ERRORLEVEL%

输出:

4

此行为记录在here.

© www.soinside.com 2019 - 2024. All rights reserved.