Func_Invoke-OneDriveApiCall.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
################################################################################
# Author : Antony Onipko
# Copyright : (c) 2016 Antony Onipko. All rights reserved.
################################################################################
# This work is licensed under the
# Creative Commons Attribution-ShareAlike 4.0 International License.
# To view a copy of this license, visit
# https://creativecommons.org/licenses/by-sa/4.0/
################################################################################

Function Invoke-OneDriveApiCall {
    <#
        .SYNOPSIS
        Wrapper for Invoke-RestMethod to send commands to the OneDrive API.
         
        .EXAMPLE
        Invoke-OneDriveApiCall -Path $path
 
        .EXAMPLE
        'drive/root:/Documents:/children' | Invoke-OneDriveApiCall
    #>

    [CmdletBinding()]
    [OutputType([PsObject])]
    Param
    (
        # API resource path.
        [Parameter(Mandatory=$True,
                   Position=1,
                   ValueFromPipeline=$True,
                   ValueFromPipelineByPropertyName=$True)]
        [Alias("ApiUrl", "Resource")]
        [string]$Path,

        # The method used for the API request.
        [Parameter(Mandatory=$False,
                   ValueFromPipelineByPropertyName=$True)]
        [Microsoft.PowerShell.Commands.WebRequestMethod]$Method,

        # Data to be sent as part of the API request.
        [Parameter(Mandatory=$False,
                   ValueFromPipelineByPropertyName=$True)]  
        $Body,

        # Gets the content of the request from the specified file.
        [Parameter(Mandatory=$False,
                   ValueFromPipelineByPropertyName=$True)]  
        [string]$InFile,

        # Saves the response to the specified path.
        [Parameter(Mandatory=$False,
                   ValueFromPipelineByPropertyName=$True)]  
        [string]$OutFile,

        # Additional headers for the request.
        [Parameter(Mandatory=$False,
                   ValueFromPipelineByPropertyName=$True)]  
        [hashtable]$AdditionalRequestHeaders
    )

    Begin {
        if ((Get-Date) -ge $PSOD.token.ExpiryDate) {
            Write-Verbose "Requesting new token."
            $token = Get-OneDriveAuthToken
            if ($token) {
                $PSOD.token = $token 
            } else {
                Write-Error "Unable to authenticate with OneDrive. Please check the configuration file."
                break
            }
        }
    }

    Process {
        
        $requestUri = joinPath $PSOD.api.url $Path

        Write-Verbose "Request URI:`n$requestUri"

        $requestHeaders = @{
            Authorization = "bearer $($PSOD.token)"
            Accept        = 'application/json'
        }

        if ($AdditionalRequestHeaders) {
            $requestHeaders += $AdditionalRequestHeaders
        }

        $irmParams = @{
            Uri         = $requestUri
            Headers     = $requestHeaders
            ContentType = 'application/json'
        }

        if ($Method) {
            $irmParams['Method'] = $Method
        }

        if ($Body) {
            $irmParams['Body'] = $Body
        }

        if ($InFile) {
            $irmParams['InFile'] = $InFile
        }

        if ($OutFile) {
            $irmParams['OutFile'] = $OutFile
        }

        try {
            $rsp = Invoke-RestMethod @irmParams
        } catch [System.Net.WebException] {
            $errorMessage = $_.ErrorDetails.Message | ConvertFrom-Json
            Write-Error "'$Path' - $($errorMessage.error.message). (Error code: $($errorMessage.error.code))"
            $httpResponse = $_.Exception.Response
            Write-Verbose "HTTP status code : $($httpResponse.StatusCode.value__)"
            Write-Verbose "HTTP status description : $($httpResponse.StatusDescription)"
        } catch {
            Write-Error $_.Exception.Message
        }

        Write-Output $rsp
    }
    
}

Export-ModuleMember -Function 'Invoke-OneDriveApiCall'