[SOLVED] Powershell, use (space-separated) string as arguments to a program

Issue

I’ve read this and it doesn’t solve my problem.

I have a space-separated string, let’s say $MyString = "arg1 arg2". Suppose I have a command line program called MyProgram, which accepts an arbitrary number of positional arguments, so it can be run like MyProgram arg1 arg2. However doing MyProgram $MyString doesn’t work, and neither does MyProgram ($MyString -split ' ') nor MyProgram $($MyString -split ' '). I get the same error which basically says that it doesn’t recognise the argument "arg1 arg2", which I guess is because it still thinks it’s one argument containing a space rather than two arguments. In practice, $MyString may be quite huge and is read from a file. How do I make this work?

Solution

Oh I just found out how LOL. I should have thought of this sooner; basically, just use splatting The following worked for me:

$MyArray = $($MyString -split " ")
MyProgram @MyArray

Explanation: The first line converts the string into an array of strings split by space (" "); The $(...) notation around a command captures the output of the command, which I then assign to $MyArray. Then, instead of using $MyArray with a dollar sign $, I use it with @ to splat the array of strings into arguments for MyProgram.

Answered By – Ray

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *