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 Hastable 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 Format
Provide value of "Filter" to output string as REST filter

.EXAMPLE
$input | ConvertTo-QueryString

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

.EXAMPLE
$input | ConvertTo-QueryString -Format Filter

Joins Key & Value with "eq"
Joins Multiple Key Value pairs with ' AND '
Formats input as: "Key%20eq%20Value%20AND%20Key%20eq%20Value"
#>


    [CmdletBinding()]
    [OutputType('System.String')]
    param(
        [parameter(
            Mandatory = $false,
            ValueFromPipeline = $true
        )]
        [hashtable]$Parameters,

        [parameter(
            Mandatory = $false,
            ValueFromPipeline = $false
        )]
        [ValidateSet("Filter")]
        [string]$Format
    )

    Begin { }

    Process {

        If ($Parameters) {

            Switch ($Format) {

                "Filter" {

                    ($Parameters.Keys | ForEach-Object {

                            "$PSItem eq $($Parameters[$PSItem])"

                        }) -join ' AND ' | Get-EscapedString

                }

                default {

                    ($Parameters.Keys | ForEach-Object {

                            "$PSItem=$($Parameters[$PSItem] | Get-EscapedString)"

                        }) -join '&'

                }

            }

        }

    }

    End { }

}