Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Start a process with unquoted arguments

Tags:

powershell

My PowerShell script should start an external executable with specified parameters. I have two strings: The file name, and the arguments. This is what process starting APIs usually want from me. PowerShell however fails at it.

I need to keep the executable and arguments in a separate strings because these are configured elsewhere in my script. This question is just about using these strings to start the process. Also, my script needs to put a common base path in front of the executable.

This is the code:

$execFile = "SomeSetup.exe"
$params = "/norestart /verysilent"
& "$basePath\$execFile" $params | Out-Host
# Pipe to the console to wait for it to finish

This is the actual result (does not work with this program):

  • Process file name: "C:\My\Base path\SomeSetup.exe"
  • Process command line: "/norestart /verysilent"

This is what I'd expect to have (this would work):

  • Process file name: "C:\My\Base path\SomeSetup.exe"
  • Process command line: /norestart /verysilent

The problem is that the setup recognises the extra quotes and interprets the two arguments as one - and doesn't understand it.

I've seen Start-Process but it seems to require each parameter in a string[] which I don't have. Splitting these arguments seems like a complicated shell task, not something I'd do (reliably).

What could I do now? Should I use something like

& cmd /c "$execFile $params"

But what if $execFile contains spaces which can well happen and usually causes much more headache before you find it.

like image 575
ygoe Avatar asked Apr 12 '26 07:04

ygoe


2 Answers

You can put your parameters in an array:

$params = "/norestart", "/verysilent"
& $basepath\$execFile $params
like image 140
Jason Shirk Avatar answered Apr 14 '26 23:04

Jason Shirk


When you run a legacy command from Powershell it has to convert the powershell variables into a single string that is the legacy command line.

  • The program name is always enclosed in quotes.
  • Any parameters that contain a space character are enclosed in double quotes (this is of course the source of your problem)
  • Each element of an array forms a separate argument.

So given:

$params = "/norestart /verysilent"
& "$basePath\$execFile" $params

Powershell will run the command:

"\somepath\SomeSetup.exe" "/norestart /verysilent"

The solution is to store separate arguments in an array:

$params = "/norestart","/verysilent"
& "$basePath\$execFile" $params

will run:

"\somepath\SomeSetup.exe" /norestart /verysilent

Or if you already have a single string:

$params = "/norestart /verysilent"
& "$basePath\$execFile" ($params -split ' ')

will work as well.

like image 29
Duncan Avatar answered Apr 15 '26 01:04

Duncan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!