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

后端 未结 2 2028
无人及你
无人及你 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:25

    The following appears to work reasonably well as a "first cut". Thanks to @briantist for the key point which was to use the .NET HttpValueCollection. It seems we have to "roll our own" way of building the query string.

    The below code snip shows a simple way to transform the hash table containing parameters and values in to a well formed query string by simply traversing the hash table. One limitation is that nesting is not permitted (a parameter value cannot be a complex type such as a hash table).

    # Setup, parameters is now a PowerShell hash table
    # we convert that on the fly to an appropriate URL
    $Parameters = @{
        Name = 'John'
        Children = 'Abe','Karen','Jo'
    }
    $Uri = 'http://example.com/somepage.php'
    $AddSquareBracketsToArrayParameters = $true
    
    
    
    $HttpValueCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
    foreach ($Item in $Parameters.GetEnumerator()) {
        if ($Item.Value.Count -gt 1) {
            # It is an array, so treat that as a special case.
            foreach ($Value in $Item.Value) {
                # Add each item in the array, optionally mark the name of the parameter
                # to indicate it is an array parameter.
                $ParameterName = $Item.Key
                if ($AddSquareBracketsToArrayParameters) { $ParameterName += '[]' }                 
                $HttpValueCollection.Add($ParameterName, $Value)
            }
        } else {
            # Add the scalar value.
            $HttpValueCollection.Add($Item.Key,$Item.Value)
        }
    }
    # Build the request and load it with the query string.
    $Request  = [System.UriBuilder]($Uri)
    $Request.Query = $HttpValueCollection.ToString()
    
    # Now fire off the request.
    Invoke-WebRequest -Uri $Request.Uri
    

提交回复
热议问题