Skip to content

Instantly share code, notes, and snippets.

@steviecoaster
Last active November 25, 2024 23:42
Show Gist options
  • Save steviecoaster/e64fbcd8163407a65ffc0397718e5e4f to your computer and use it in GitHub Desktop.
Save steviecoaster/e64fbcd8163407a65ffc0397718e5e4f to your computer and use it in GitHub Desktop.
Creates a querystring to use with an API call
function New-QueryString {
<#
.SYNOPSIS
Turn a hashtable into a URI querystring
.DESCRIPTION
Turn a hashtable into a URI querystring
.PARAMETER QueryParameter
The hashtable to transform
.EXAMPLE
New-QueryString -QueryParameter @{ Animal = 'Dog'; Breed = 'Labrador; Name = 'Dilbert'}
.NOTES
Shamelessly taken from https://powershellmagazine.com/2019/06/14/pstip-a-better-way-to-generate-http-query-strings-in-powershell/
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[Hashtable]
$QueryParameter
)
# Add System.Web
Add-Type -AssemblyName System.Web
# Create a http name value collection from an empty string
$nvCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
foreach ($key in $QueryParameter.Keys) {
$nvCollection.Add($key, $QueryParameter.$key)
}
return $nvCollection.ToString()
}
@joshooaj
Copy link

Hi @steviecoaster! I added support for accepting IDictionary and handling for values that implement ICollection so that the resulting query string can support multiple values with the same key based on comments from @StartAutomating on bsky:

https://gist.github.com/joshooaj/1f2ca6153b2085a9e028e9860f209c9a

@StartAutomating
Copy link

Lol now if only there was some GitHub org I'd made with the express purpose of collecting PowerShell web stuff.

Oh wait.....

Https://GitHub.com/PowerShellWeb

Who wants an invite ?

@joshooaj
Copy link

Obvs me 😁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment