Private/Add-UriQueryParam.ps1
|
<#
.SYNOPSIS Append or replace a query parameter on a URI string. .DESCRIPTION Adds a query parameter to the given URI. If the parameter already exists, its value is replaced. Optionally converts wildcard characters (* and ?) to SQL-style patterns (% and _). .PARAMETER Uri The URI string to modify. Accepts pipeline input. .PARAMETER Query The query parameter in 'key=value' format. .PARAMETER ConvertWildcards If set, converts '*' to '%' and '?' to '_' in the query value before appending. .EXAMPLE PS> "https://duneframework.com/api/items" | Add-UriQueryParam -Query "name=test" Appends '?name=test' to the URI. #> function Add-UriQueryParam { param( [Parameter(Mandatory, ValueFromPipeline)] [string]$Uri, [Parameter(Mandatory, Position = 0)] [string]$Query, [Parameter()] [switch]$ConvertWildcards ) begin {} process { if ($ConvertWildcards) { $Query = $Query.Replace('*', '%').Replace('?', '_') } $JoinChar = if ($Uri.Contains('?')) { '&' } else { '?' } $Key, $Value = $Query -split '=' if ($Uri -match "[?&]$Key=*") { Write-Debug $('Replacing existing query parameter {0} with {1}.' -f $Key, $Value) $Uri -replace "($Key=)[^&]*", "$Key=$Value" } else { $Uri, $Query -join $JoinChar } } end {} } |