-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertTo-QueryString.ps1
68 lines (67 loc) · 2.59 KB
/
ConvertTo-QueryString.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function ConvertTo-QueryString {
[CmdletBinding(DefaultParameterSetName = "IDictionary")]
[OutputType([string])]
param(
[parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName = "IDictionary")]
[AllowNull()]
[AllowEmptyCollection()]
[System.Collections.IDictionary]
$InputObject,
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "NameValueCollection")]
[AllowNull()]
[AllowEmptyCollection()]
[System.Collections.Specialized.NameValueCollection]
$NameValueCollection
)
begin {
$t = @()
}
process {
if ($InputObject -ne $null) {
foreach ($kv in $InputObject.GetEnumerator()) {
$key = $kv.Key
$list = $kv.Value
if (IsEmpty $list) {
$list = @( [string]::Empty )
}
else {
$list = ToString $list
}
foreach ($value in $list) {
if ([string]::IsNullOrEmpty($key)) {
#Write-Host "ConvertTo-QueryString: '$value'"
$t += [System.Net.WebUtility]::UrlEncode($value)
}
else {
#Write-Host "ConvertTo-QueryString: '$key'='$value'"
$t += [System.Net.WebUtility]::UrlEncode($key), [System.Net.WebUtility]::UrlEncode($value) -join "="
}
}
}
}
if ($NameValueCollection -ne $null) {
foreach ($key in $NameValueCollection.AllKeys) {
$list = $NameValueCollection.GetValues($key)
if (IsEmpty $list) {
$list = @( [string]::Empty )
}
else {
$list = ToString $list
}
foreach ($value in $list) {
if ([string]::IsNullOrEmpty($key)) {
#Write-Host "ConvertTo-QueryString: '$value'"
$t += [System.Net.WebUtility]::UrlEncode($value)
}
else {
#Write-Host "ConvertTo-QueryString: '$key'='$value'"
$t += [System.Net.WebUtility]::UrlEncode($key), [System.Net.WebUtility]::UrlEncode($value) -join "="
}
}
}
}
}
end {
$PSCmdlet.WriteObject(($t -join "&"), $false)
}
}