【问题标题】:How to run a command with options and store exit code in a variable如何使用选项运行命令并将退出代码存储在变量中
【发布时间】: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 文件返回的退出代码分配给变量。

到目前为止,这是我尝试过的:

  1. 尝试了以下语法:
$myVariable | & $myExe @options

但是变量没有被赋值

  1. 使用过的 Tee 对象
& $myExe @options | Tee-Object $myVariable

但我得到一个 ParameterBindingValidationException 错误

  1. 创建了一个 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


【解决方案1】:

可执行文件退出后,PowerShell 将使用退出代码填充$LASTEXITCODE 变量:

$myExe="C:\MyProgram\mycommand.exe"
$options = @(
                "--option1=value1"
                "--option2=value2"
                "--option3=value3"
            )
$outputFromExe = & $myExe @options

return [pscustomobject]@{
  Program = $myExe
  ExitCode = $LASTEXITCODE
  Output = $outputFromExe
}

【讨论】:

    猜你喜欢
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多