How to use GET method of Invoke-WebRequest to build a query string

后端 未结 2 2033
无人及你
无人及你 2021-02-15 16:22

Is there a standard way to make use of Invoke-WebRequest or Invoke-RestMethod in PowerShell to get information from a web page using a query string?

For example, I know

2条回答
  •  再見小時候
    2021-02-15 16:37

    It seems that the server running PHP is irrelevant here. I think you're asking how to send key/value pairs as query string parameters.

    If that's the case, you're in luck. Both Invoke-RestMethod and Invoke-WebRequest will take a [hashtable] in the body and construct your query string for you:

    $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
    

    Edit

    Now seeing that the issue is that you want a query string parameter to have multiple values, essentially an array, this rules out the data types you can pass to the body parameter.

    So instead, let's build the URI piece by piece first by starting with a [UriBuilder] object and adding on a query string built using an [HttpValueCollection] object (which allows duplicate keys).

    $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
    

提交回复
热议问题