PowerShell Add Parameters to Command / For-Each?

0

Issue

So, I’m in PowerShell and I can run a command like…

& .\curl.exe -vk -u <username:password> -F <some data> -F <some more data> --url <url here>

That all works fine, but sometimes there are more data entries to add, so more "-F"s to add. Like…

& .\curl.exe -vk -u <username:password> -F <some data> -F <some more data> -F <more data> -F <and another one> --url <url here>

I’ve tried creating foreach loops and building a long ScriptBlock but it doesn’t seem to like that if I use the created string and Invoke-Command. Like this…

$Data = @()
$Data += "some data"
$Data += "more data"
$Data += "even more data"

$Script = @()
$Script += "& .\curl.exe -vk -u <username:password>"
foreach ($D in $Data) {
    $Script += "-F $D"
}
$Script += "--url <url here>"

$FinalScript = $Script -join ' '

Invoke-Command -ScriptBlock {$FinalScript}

Any help welcome. Sorry if this is not in the correct format… Newb! Oh and this is on PowerShell 5.1… because Windows!

Solution

One option is to construct an array of -F <string> sequences you want to pass to curl and then use the @ splatting operator:

# define the data contents
$data = @(
  "some data"
  "more data"
  "additional data"
)

# prepend each data item with `-F`, store the resulting sequence in a new array
$Fparams = $data |ForEach-Object { '-F', $_ }

# invoke application and pass -F params with the @ splatting operator
& .\curl.exe -vk -u <username:password> @Fparams

Answered By – Mathias R. Jessen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More