1

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!

mklement0
  • 382,024
  • 64
  • 607
  • 775
Neil
  • 41
  • 4

2 Answers2

3

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Perfect. I read about "Splatting" but didn't quite get it. Makes sense like this. Thank you very much! – Neil Nov 02 '21 at 14:59
1

The values "some data", "more data" etc. contain spaces and so you need to use quotes around them.

As it is now, your code outputs:

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

Try

$Data      = "some data", "more data", "even more data"
$Script    = "& .\curl.exe -vk -u <username:password> @@F@@ --url <url here>"
$fSwitches = $(foreach ($D in $Data) { '-F "{0}"' -f $D }) -join ' '

$FinalScript = $Script -replace '@@F@@', $fSwitches

$FinalScript will now contain

& .\curl.exe -vk -u <username:password> -F "some data" -F "more data" -F "even more data" --url <url here>
Theo
  • 57,719
  • 8
  • 24
  • 41