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.
CodePudding user response:
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}
CodePudding user response:
$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 code, and the result of which is a piece of PowerShell code meant for later execution on demand.
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, which the intrinsic .ForEach()
method facilitates:
# Note: Assumes that `doSomething` is an *external program*
dosomething $values.ForEach({ '-a', $_ })