Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a legacy command with values from array

Tags:

powershell

I have a legacy command foo which accepts arbitrarily many (identically named) input parameters, each prefixed by --input. From cmd.exe, I can run:

C:\> foo --input "first" --input "second" --input "third" file.dat

and three input values are used to process file.dat.

I am trying call foo from a Powershell script in which I can calculate an array which has values/types which might be equivalent to these constant values.

$my_args = @(
  "first",
  "second",
  "third"
)

I want to be able to call foo so that the arguments --include <value> are repeated for each item in $my_args. I could use:

foo --input $my_args[0] --input $my_args[1] --input $my_args[2] filename.dat

but this wouldn't work if $my_args did not contain exactly 3 items. What would be a neat Powershell idiom to do this?

like image 713
aSteve Avatar asked Nov 17 '25 07:11

aSteve


1 Answers

So you could technically do a loop, adding the --input parameter to every item in $my_args, like so:

$my_args = @(
    'first',
    'second',
    'third'
)

$my_args = $my_args | ForEach-Object { '--input', $_ }

And then you can append that last argument filename.dat to your arguments array:

$my_args += 'filename.dat'

This would also work to do everything in one go:

$my_args = @(
    $my_args | ForEach-Object { '--input', $_ }
    'filename.dat')

And then you could splat them like this:

foo @my_args

Another way to do it, based on your own comment ;) that should work as well but is perhaps less readable can be:

# in different lines
foo @(
    $my_args | ForEach-Object { '--input', $_ }
    'filename.dat')

# or in a single lines, you'd use `;` to separate the statements
foo @($my_args | ForEach-Object { '--input', $_ }; 'filename.dat')
like image 162
Santiago Squarzon Avatar answered Nov 19 '25 20:11

Santiago Squarzon



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!