Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 476
Ray Avatar asked May 14 '26 10:05

Ray


1 Answers

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.

like image 85
Ray Avatar answered May 18 '26 16:05

Ray



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!