gpt4 book ai didi

powershell - 使用 Start-Process 和 WaitForExit 而不是 -Wait 获取 ExitCode

转载 作者:行者123 更新时间:2023-12-02 22:47:26 26 4
gpt4 key购买 nike

我正在尝试从 PowerShell 运行程序,等待退出,然后访问 ExitCode,但我运气不佳。我不想将 -WaitStart-Process 一起使用,因为我需要在后台进行一些处理。

这是一个简化的测试脚本:

cd "C:\Windows"

# ExitCode is available when using -Wait...
Write-Host "Starting Notepad with -Wait - return code will be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru -Wait)
Write-Host "Process finished with return code: " $process.ExitCode

# ExitCode is not available when waiting separately
Write-Host "Starting Notepad without -Wait - return code will NOT be available"
$process = (Start-Process -FilePath "notepad.exe" -PassThru)
$process.WaitForExit()
Write-Host "Process exit code should be here: " $process.ExitCode

运行此脚本将导致 Notepad即将开始。手动关闭后,会打印退出代码,然后再次启动,无需使用-wait。退出时不提供 ExitCode:

Starting Notepad with -Wait - return code will be available
Process finished with return code: 0
Starting Notepad without -Wait - return code will NOT be available
Process exit code should be here:

我需要能够在启动程序和等待程序退出之间执行额外的处理,因此我无法使用-Wait。我怎样才能做到这一点并且仍然可以从此进程访问 .ExitCode 属性?

最佳答案

这里有两件事需要记住。一是添加 -PassThru 参数,二是添加 -Wait 参数。您需要添加等待参数,因为 this defect .

-PassThru [<SwitchParameter>]
Returns a process object for each process that the cmdlet started. By default,
this cmdlet does not generate any output.

执行此操作后,进程对象将被传回,您可以查看该对象的 ExitCode 属性。这是一个例子:

$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode

# This will print 1

如果您在没有 -PassThru-Wait 的情况下运行它,它将不会打印任何内容。

同样的答案在这里: How do I run a Windows installer and get a succeed/fail value in PowerShell?

还值得注意的是,上面的“缺陷报告”链接中提到了一种解决方法,如下:

# Start the process with the -PassThru command to be able to access it later
$process = Start-Process 'ping.exe' -WindowStyle Hidden -ArgumentList '-n 1 -w 127.0.0.1' -PassThru

# This will print out False/True depending on if the process has ended yet or not
# Needs to be called for the command below to work correctly
$process.HasExited

# This will print out the actual exit code of the process
$process.GetType().GetField('exitCode', 'NonPublic, Instance').GetValue($process)

关于powershell - 使用 Start-Process 和 WaitForExit 而不是 -Wait 获取 ExitCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com