functions/Private/Converting/ConvertTo-MgaQuery.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
function ConvertTo-MgaQuery {
    param (
        $Uri,
        $Top,
        $Skip,
        $Count,
        $OrderBy,
        $Expand,
        $Select
    )
    function Update-Query {
        param (
            $Query,
            $Uri,
            [bool]$QueryEnabled
        )
        if ($QueryEnabled -eq $true) {
            $Query = "&$Query"
        }
        else {
            $Query = "?$Query"           
        }
        $Uri = "$Uri$Query"
        return $Uri, $true
    }
    $QueryEnabled = $false
    if ($Top) {
        $Query = "`$top=$Top"
        $Result = Update-Query -Query $Query -Uri $Uri -QueryEnabled $QueryEnabled
        $Uri = $Result[0]
        $QueryEnabled = $Result[1]
    } 
    if ($Skip) {
        $Query = "`$Skip=$Skip"
        $Result = Update-Query -Query $Query -Uri $Uri -QueryEnabled $QueryEnabled
        $Uri = $Result[0]
        $QueryEnabled = $Result[1]
    } 
    if ($Count) {
        $Query = "`$Count=$Count"
        $Result = Update-Query -Query $Query -Uri $Uri -QueryEnabled $QueryEnabled
        $Uri = $Result[0]
        $QueryEnabled = $Result[1]
    }
    if ($OrderBy) {
        $Query = "`$OrderBy=$OrderBy"
        $Result = Update-Query -Query $Query -Uri $Uri -QueryEnabled $QueryEnabled
        $Uri = $Result[0]
        $QueryEnabled = $Result[1]
    }
    if ($Expand) {
        $Query = "`$Expand=$Expand"
        $Result = Update-Query -Query $Query -Uri $Uri -QueryEnabled $QueryEnabled
        $Uri = $Result[0]
        $QueryEnabled = $Result[1]
    }
    if ($Select) {
        $i = 1
        foreach ($Property in $Select) {
            if ($i -eq $Select.Count) {
                $SelectString += $Property
            }
            else {
                $i++
                $SelectString += "$Property,"
            }   
        }
        $Query = "`$Select=$SelectString"
        $Result = Update-Query -Query $Query -Uri $Uri -QueryEnabled $QueryEnabled
        $Uri = $Result[0]
        $QueryEnabled = $Result[1]
    }
    if ($QueryEnabled -eq $true) {
        Write-Verbose "Added Query Parameters: $Uri"
    }
    return $Uri
}