[英]How do I get the ErrorLevel from a process started via PowerShell Start-Process called from CMD?
I'd like to be able to get the ErrorLevel of Process.exe from this example command:我希望能够从此示例命令中获取 Process.exe 的 ErrorLevel:
C:\>PowerShell -NoP -C "Start-Process "C:\Process.exe""
If Process.exe exits with an ErrorLevel of 5, I'd like to be able to capture that via CMD, ideally in the %ErrorLevel% variable.如果 Process.exe 以 5 的 ErrorLevel 退出,我希望能够通过 CMD 捕获它,最好是在 %ErrorLevel% 变量中。 I'm not proficient enough in PowerShell to do this.
我对 PowerShell 不够熟练,无法做到这一点。
Use the following, assuming that C:\process.exe
is a console application : [1]使用以下内容,假设
C:\process.exe
是一个控制台应用程序: [1]
PowerShell -NoP -C "C:\Process.exe; exit $LASTEXITCODE"
Note: If the executable path contains spaces, enclose it in '...'
;注意:如果可执行文件路径包含空格,请将其括在
'...'
中; if it contains '
itself, either escape the enclosed '
chars.如果它包含
'
本身,要么转义封闭'
字符。 as ''
, or enclose the path in \"...\"
(sic) instead - see this answer for more information.作为
''
,或将路径括在\"...\"
(原文如此)中 - 请参阅此答案以获取更多信息。
In order to get a process' exit code, you must wait for it to terminate.为了获得进程的退出代码,您必须等待它终止。
Start-Process
does not wait for termination by default, unless you add the -Wait
switch - but then you'd also need -PassThru
in order to return a process-information object whose .ExitCode
property you'd need to report via exit
. Start-Process
默认情况下不会等待终止,除非您添加-Wait
开关 - 但是您还需要-PassThru
才能返回进程信息 object 您需要通过exit
报告其.ExitCode
属性。
Direct execution of the target executable, as shown above, (a) results in synchronous execution of console applications [1] to be begin with and (b) automatically reflects the process exit code in the automatic $LASTEXITCODE
variable variable.直接执行目标可执行文件,如上所示,(a) 导致开始的控制台应用程序[1]的同步执行,以及 (b) 在自动变量
$LASTEXITCODE
变量中自动反映进程退出代码。
Without the exit $LASTEXITCODE
statement, the process' exit code would be mapped to an abstracted exit code: 0
(success) would be reported as-is, but any nonzero exit code would be mapped to 1
- see this post for more information.如果没有
exit $LASTEXITCODE
语句,进程的退出代码将映射到抽象的退出代码: 0
(成功)将按原样报告,但任何非零退出代码将映射到1
- 请参阅此帖子了解更多信息。
Either way, PowerShell
's ( powershell.exe
's) exit code will be reflected in cmd.exe
's dynamic %ErrorLevel%
variable.无论哪种方式,
PowerShell
的( powershell.exe
的)退出代码将反映在cmd.exe
的动态%ErrorLevel%
变量中。
[1] If your application happens to be a GUI -subsystem application, you'll indeed need a Start-Process
-based solution; [1] 如果您的应用程序恰好是一个GUI子系统应用程序,您确实需要一个基于
Start-Process
的解决方案; as you've noted in a comment yourself, the solution would be:正如您自己在评论中指出的那样,解决方案是:
PowerShell -NoP -C "exit (Start-Process 'C:\Process.exe' -Wait -PassThru).ExitCode"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.