使用 System.Web.HttpUtilityUrlEncode() 編碼查詢字串

$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 = [System.Web.HttpUtility]::UrlEncode($qs.Name)
    $qs_value = [System.Web.HttpUtility]::UrlEncode($qs.Value)
    $qs_array.Add("${qs_key}=${qs_value}") | Out-Null
}

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

使用 [System.Web.HttpUtility]::UrlEncode(),你會注意到空格變成了加號(+)而不是%20

https://example.vertigion.com/foos ?foo2 =複合%3b%2f%3f%3a%40%26%3d%2b%24%2c + bar%27%22&複合%3b%2f%3f%3a%40%26%3d%2b%24%2c + FOO%27%22 = BAR2&foo1 = BAR1