Private/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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Function ConvertTo-QueryString {
    <#
.SYNOPSIS
Converts Hashtable to a string for use as a url query string

.DESCRIPTION
When given a hashtable as input, converts key value pairs to query string

.PARAMETER Parameters
Hashtable containing parameter names and values to include in output string

.PARAMETER NoEscape
Specify to perform no escaping on the returned string.

.EXAMPLE
$input | ConvertTo-QueryString

Joins Key & Value with "="
Joins Multiple Key Value pairs with '&'
Formats input as: "Key=Value&Key=Value"

#>

    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'FilterList', Justification = "False Positive")]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'NoEscape', Justification = "False Positive")]
    [CmdletBinding()]
    [OutputType('System.String')]
    param(
        [parameter(
            Mandatory = $false,
            ValueFromPipeline = $true
        )]
        [hashtable]$Parameters,

        [parameter(
            Mandatory = $false,
            ValueFromPipeline = $false
        )]
        [switch]$NoEscape
    )

    Begin { }

    Process {

        If ($Parameters) {

            $Parameters.Keys | ForEach-Object {

                $FilterList = [Collections.Generic.List[Object]]@()

            } {

                If ($NoEscape) {

                    #Return Key=Value string, unescaped.
                    $Value = "$PSItem=$($Parameters[$PSItem])"

                }
                Else {

                    #Return Key=Value string, escaped.
                    $Value = "$PSItem=$($Parameters[$PSItem] | Get-EscapedString)"

                }

                $null = $FilterList.Add($Value)

            } {

                If ($FilterList.count -gt 0) {

                    $FilterList -join "&"

                }
            }

        }

    }

    End { }

}