PowerShell 将参数添加到命令/For-Each?

PowerShell Add Parameters to Command / For-Each?

所以,我在 PowerShell 中,我可以 运行 命令如...

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

一切正常,但有时需要添加更多数据条目,因此需要添加更多“-F”。喜欢...

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

我已经尝试创建 foreach 循环并构建一个长 ScriptBlock,但如果我使用创建的字符串和 Invoke-Command,它似乎并不喜欢那样。像这样...

$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}

欢迎任何帮助。抱歉,如果格式不正确...新手!哦,这是在 PowerShell 5.1 上...因为 Windows!

一个选项是构建一个包含要传递给 curl 的 -F <string> 序列的数组,然后使用 @ 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

"some data""more data" 等包含空格,因此您需要在它们周围使用引号。

就像现在一样,您的代码输出:

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

尝试

$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 现在将包含

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