有没有办法在从 Powershell 发布 api 调用时将表单数据转换为 x-www-form-urlencoded 格式?

问题描述 投票:0回答:1

我正在 VSCode 中编写 powershell 脚本。

在尝试将表单数据转换为 x-www-form-urlencoded 格式时,我不断遇到上述问题。

我有一个表单数据如下:

$formData = @{
    'grant_type' = 'password'
    'scope' = 'xyz'
    'client_id' = 'xyzAPIClient'
    'client_secret' = 'xyzabcdef'
    'username' = '[email protected]'
    'password' = 'password1'
}

我尝试将其转换为 x-www-form-urlencoded 格式,以便按如下方式使用它(向服务器发布请求):

$formUrlEncoded = $formData | ForEach-Object {"$($_.Key)=$($_.Value)"} -join '&'
$response = Invoke-RestMethod -Uri $apiEndPoint -Method Post -Body $formUrlEncoded -Headers $headers

我遇到以下问题

ForEach-Object : Cannot bind parameter 'RemainingScripts'. Cannot convert the "-join" value of type "System.String" to type 
"System.Management.Automation.ScriptBlock".
At C:\Automation\automation-scripts\automation-getToken.ps1:15 char:31
+ ... oded = $formData | ForEach-Object {"$($_.Key)=$($_.Value)"} -join '&'
+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.ForEachObjectCommand

我是 powershell 新手,我不明白是什么导致了这个问题。有人可以帮忙吗

powershell form-data x-www-form-urlencoded
1个回答
0
投票

您正在使用哈希表,您无法以这种方式访问它

这应该有效

$formUrlEncoded = ($formdata.keys | ForEach-Object { "$_=$($formdata.$_)" }) -join '&'

© www.soinside.com 2019 - 2024. All rights reserved.