MrGoodfellow
MrGoodfellow

Reputation: 89

Passing Multiple Values to a Command in PowerShell

I'm trying to pass an array of arguments to a command in PowerShell.
I'm not sure how to tell it to loop through the arguments and execute the code properly.

Here is my array example:

$values = {value1, value2, value3...}

Here is my command example:

dosomething -a value1 -a value2 -a value3

I tried using a foreach but I just can't figure out the syntax.

dosomething {foreach($value in $values) {-a $value}}

I feel like I'm very close but missing something.

Upvotes: 2

Views: 1417

Answers (2)

mklement0
mklement0

Reputation: 437823

$values = {value1, value2, value3...}

Unless value1, etc. are placeholders for numbers (e.g., 42) or strings (e.g., 'foo'), this is invalid syntax, given that { ... } creates a script block, the content of which must be valid PowerShell source code, and the result of which is a piece of PowerShell code meant for later execution on demand, such as with &, the call operator or ., the dot-sourcing operator

In order to create an array, simply use , to separate the elements or enclose them in @(...), the array-subexpression operator:

$values = 'value1', 'value2', 'value3' # , ...

# explicit alternative
$values = @( 'value1', 'value2', 'value3' )

The fact that you're looking to pass multiple -a arguments implies that you're calling an external program:

  • PowerShell-native commands do not allow targeting a given parameter multiple times.

When calling external programs, you can pass both parameter names and values as a flat array of string arguments:

# Note: Assumes that `doSomething` is an *external program*
dosomething $values.ForEach({ '-a', $_ })
  • Alternatively, you may use @(...) or - in this case, interchangeably - $(...), the subexpression operator to pass the output from arbitrary commands as individual arguments:
# Note: Assumes that `doSomething` is an *external program*

# Using a pipeline.
dosomething $($values | ForEach-Object { '-a', $_ })

# Using a foreach statement.
dosomething $(foreach ($value in $values) { '-a', $value })

Upvotes: 1

MrGoodfellow
MrGoodfellow

Reputation: 89

Thank you Santiago Squarzon!

here is my working code concept:

$zones = {domain.com, domain.net, domain.ect...}
certbot @(foreach ($zone in $zones) { '-d', $zone})

as an extra step I can can import and convert the zones from a csv file (example zones.csv):

Sites
domain.com
domain.net
domain.ect

Then import and convert the Sites to an array in PowerShell:

$zones = Import-csv -Path zones.csv

$zones = foreach ($site in $zones.sites) {$site}

Upvotes: 0

Related Questions