3

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?

2
  • 2
    Try this: stackoverflow.com/questions/2081795/… Commented Jun 20, 2014 at 8:57
  • Okay, that gives me the correct return code today. There's still the console redirection issue. I don't get any coloured output and the executed process cannot determine its console window size or move the cursor. Commented Jun 20, 2014 at 9:19

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.