【发布时间】:2020-10-26 21:58:26
【问题描述】:
您好 Stack Overflow 专家
我目前正在尝试从 PowerShell 脚本运行 exe 文件,并希望将退出代码存储在变量中。
如果单独从Windows命令行运行,语法如下:
C:\MyProgram\mycommand.exe --option1=value1 --option2=value2 --option3=value3
在 Powershell 中,我可以使用调用运算符运行上述代码:
$myExe="C:\MyProgram\mycommand.exe"
$options = @(
"--option1=value1"
"--option2=value2"
"--option3=value3"
)
& $myExe @options
但我不确定如何将 exe 文件返回的退出代码分配给变量。
到目前为止,这是我尝试过的:
- 尝试了以下语法:
$myVariable | & $myExe @options
但是变量没有被赋值
- 使用过的 Tee 对象
& $myExe @options | Tee-Object $myVariable
但我得到一个 ParameterBindingValidationException 错误
- 创建了一个 System.Diagnostics.Process 对象
$ps = New-Object System.Diagnostics.Process
$ps.StartInfo.FileName = "C:\MyProgram\mycommand.exe"
$ps.StartInfo.Arguments = "--option1=value1 --option2=value2 --option3=value3"
$ps.StartInfo.RedirectStandardOutput = $True
$ps.StartInfo.UseShellExecute = $False
$ps.Start()
$ps.WaitForExit()
这允许我通过调用 $ps.ExitCode 来获取退出代码,但 exe 运行不正确。 没有抛出错误,但似乎没有正确读取选项。
关于如何实现这一点的任何建议?
【问题讨论】:
-
$lastexitcode 应该已经包含它了?
-
是什么让你觉得exe运行不正常?
标签: powershell