如何使用Invoke-WebRequest的GET方法来构建查询字符串

use*_*092 8 arrays powershell json

有没有一种标准方法可以使用PowerShell中的Invoke-WebRequest或Invoke-RestMethod来使用查询字符串从网页获取信息?

例如,我知道使用格式良好的JSON端点时,以下内容将起作用:

$Parameters = @{
  Name = 'John'
  Children = 'Abe','Karen','Jo'
}
$Result = Invoke-WebRequest -Uri 'http://.....whatever' -Body ( $Parameters | ConvertTo-Json)  -ContentType application/json -Method Get
Run Code Online (Sandbox Code Playgroud)

以及等效的Invoke-WebMethod.其中一个重要方面是内容类型和ConvertTo-JSON,它管理-Body部分中指定的参数到标准形式的转换,包括"Children"字段的数组方面.

有一个等效的方法是使用一个网站,例如,使用逗号分隔的约定来管理URL中的数组参数或方法,如"Children [] = Abe&Children [] = Karen&Children = Jo"?

是否有我缺少的内容类型,并且有一个等价的ConvertTo- ?? 我可以用吗?我的猜测是有人不得不这样做.

对于上下文,这是一种在URL中编码数组参数的常用方法,常见于PHP网站.

将数组作为url参数传递

编辑 删除对PHP的引用,但特定上下文除外,并调整标题以引用查询字符串.问题是关于编码查询字符串而不是PHP本身.

bri*_*ist 6

似乎运行PHP的服务器在这里无关紧要。我认为您在问如何将键/值对作为查询字符串参数发送。

如果真是这样,那么您很幸运。两者Invoke-RestMethodInvoke-WebRequest都将[hashtable]在正文中为您并为您构造查询字符串:

$Parameters = @{
  Name = 'John'
  Children = 'Abe','Karen','Jo'
}
Invoke-WebRequest -Uri 'http://www.example.com/somepage.php' -Body $Parameters -Method Get # <-- optional, Get is the default
Run Code Online (Sandbox Code Playgroud)

编辑

现在看到的问题是,您希望查询字符串参数具有多个值,本质上是一个数组,这排除了您可以传递给body参数的数据类型。

因此,让我们首先从一个[UriBuilder]对象开始,然后添加一个使用[HttpValueCollection]对象(允许重复键)构建的查询字符串,逐步构建URI 。

$Parameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
$Parameters['Name'] = 'John'
foreach($Child in @('Abe','Karen','Joe')) {
    $Parameters.Add('Children', $Child)
}

$Request = [System.UriBuilder]'http://www.example.com/somepage.php'

$Request.Query = $Parameters.ToString()

Invoke-WebRequest -Uri $Request.Uri -Method Get # <-- optional, Get is the default
Run Code Online (Sandbox Code Playgroud)