使用 uriEscapeDataString() 編碼查詢字串

$scheme = 'https'
$url_format = '{0}://example.vertigion.com/foos?{1}'
$qs_data = @{
    'foo1'='bar1';
    'foo2'= 'complex;/?:@&=+$, bar''"';
    'complex;/?:@&=+$, foo''"'='bar2';
}

[System.Collections.ArrayList] $qs_array = @()
foreach ($qs in $qs_data.GetEnumerator()) {
    $qs_key = [uri]::EscapeDataString($qs.Name)
    $qs_value = [uri]::EscapeDataString($qs.Value)
    $qs_array.Add("${qs_key}=${qs_value}") | Out-Null
}

$url = $url_format -f @([uri]::"UriScheme${scheme}", ($qs_array -join '&'))

使用 [uri]::EscapeDataString(),你會注意到撇號(')未被編碼:

https://example.vertigion.com/foos ?foo2 =複數%3B%2F%3F%3A%40%26%3D%2B%24%2C%20bar’%22&複合%3B%2F%3F%3A%40%26%3D%2B%24%2C% 20foo’%22 = BAR2&foo1 = BAR1