从 PowerShell 执行控制台应用程序

ygo*_*goe 2 powershell

在本身就是控制台应用程序的 PowerShell 脚本中,我需要执行另一个具有任意名称、参数、无流重定向的控制台应用程序,并获得正确的返回代码。

这是我当前的代码:

$execFile = "C:\Path\To\Some.exe"
$params = "arg1 arg2 /opt3 /opt4"

# Wait until the started process has finished
Invoke-Expression ($execFile + " " + $params + " | Out-Host")
if (-not $?)
{
    # Show error message
}
Run Code Online (Sandbox Code Playgroud)

它可以使用正确的参数启动 Win32 应用程序(空格分隔参数,并非所有内容都进入 argv[1])。但是返回码好像丢了,还重定向了控制台流。那是行不通的。

另一个代码也是错误的:

& $execFile $params
if (-not $?)
{
    # Show error message
}
Run Code Online (Sandbox Code Playgroud)

当这获取返回码并等待进程完成时,它将所有参数放入 argv[1] 并且执行的进程无法使用该垃圾输入。

PowerShell 中还有其他解决方案吗?

Jas*_*irk 5

您使用调用运算符 & 的想法是正确的 - 但您需要将参数作为数组而不是单个值传递。

当参数是单个值时,PowerShell 假定您希望该值作为单个值传递 - 有时这意味着在构建命令行时添加引号。此行为是预期的,因为它匹配将字符串传递给 PowerShell 命令,例如,如果您尝试过:

$path = "C:\Program Files"
dir $path
Run Code Online (Sandbox Code Playgroud)

您希望这将单个值传递给 dir,而不是多个值。

如果参数是一个数组,PowerShell 会在构建命令行传递给 exe 时在每个数组元素之间放置空格。

尝试:

$execFile = "C:\Path\To\Some.exe"
$params = "arg1","arg2","/opt3","/opt4"

# Wait until the started process has finished
& $execFile $params
if (-not $?)
{
    # Show error message
}
Run Code Online (Sandbox Code Playgroud)