ygoe
ygoe

Reputation: 20414

Execute a console application from PowerShell

In a PowerShell script that is itself a console application, I need to execute another console application with an arbitrary name, parameters, no stream redirection and get the correct return code.

This is my current code:

$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
}

It can start Win32 applications with the correct parameters (spaces delimit parameters, not everything goes into argv[1]). But the return code seems to be lost, and it also redirects console streams. That just doesn't work.

Another code is also wrong:

& $execFile $params
if (-not $?)
{
    # Show error message
}

While this gets the return code and waits for the process to finish, it puts all parameters into argv[1] and the executed process can't work with that garbage input.

Is there another solution in PowerShell?

Upvotes: 3

Views: 8568

Answers (1)

Jason Shirk
Jason Shirk

Reputation: 8019

You've got the right idea using the invocation operator & - but you need to pass your arguments as an array instead of a single value.

When the argument is a single value, PowerShell assumes you want that value passed as a single value - sometimes that means adding quotes when building the command line. This behavior is expected because it matches passing a string to PowerShell commands, e.g. if you tried:

$path = "C:\Program Files"
dir $path

You'd expect this to pass a single value to dir, not multiple values.

If the argument is an array, PowerShell will put spaces between each array element when building the command line to pass to the exe.

Try:

$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
}

Upvotes: 5

Related Questions