MicrosoftGraphAPI.psm1

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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
<#
.Synopsis
    Get a oAuth token to access Microsoft Graph API
.DESCRIPTION
    Get a oAuth token to access Microsoft Graph API. Token will be valid for 2 hours.
.EXAMPLE
    Get-GraphAuthToken -AADTenant "runbookguru.onmicrosoft.com" -ClientId "cdec3c46-b1cd-4ce7-859a-b6fac1ceafee" -RedirectUri "http://www.runbook.guru" -Credential (get-credential)
.NOTES
This is a preview/beta version. Please send any comments to jgs@coretech.dk
Developed by MVP Jakob Gottlieb Svendsen - jakob@runbook.guru - jgs@coretech.dk
.LINK
    http://graph.microsoft.io/
#>

function Get-GraphAuthToken
{
    [CmdletBinding(DefaultParameterSetName='Default', 
                  SupportsShouldProcess=$false, 
                  PositionalBinding=$false,
                  HelpUri = 'http://www.runbook.guru/')]
   param (
    [Parameter(Mandatory=$true,ParameterSetName=’Connetion’)]
    [Hashtable] $Connection, 
        #Connection
        #"Name": "AADTenantName"
        #"Name": "ClientId"
        #"Name": "RedirectUri"
        #"Name": "UserName"
        #"Name": "Password"
    [Parameter(Mandatory=$true,ParameterSetName=’Default’)] 
    [String] $AADTenant, 
    [Parameter(Mandatory=$true,ParameterSetName=’Default’)]
    [String] $ClientId,
    [Parameter(Mandatory=$true,ParameterSetName=’Default’)]
    [String]$RedirectUri,
    [Parameter(Mandatory=$true,ParameterSetName=’Default’)]
    [PSCredential] $Credential
    )
   
   #On Connection
   if($Connection)
   {   
      $AADTenant = $Connection.AADTenantName
      $ClientId = $Connection.ClientId
      $RedirectUri = $Connection.RedirectUri
    
      $username = $Connection.UserName
      $password = $Connection.Password | ConvertTo-SecureString -AsPlainText -Force
      $Credential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
   }
    
   $Modulebase = (get-Module MicrosoftGraphAPI).ModuleBase

   $adal = "$Modulebase\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" 
   $adalforms = "$Modulebase\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"
   
   [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
   [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
   
   $resourceAppIdURI = “https://graph.microsoft.com”
   
   $authority = “https://login.windows.net/$aadTenant”
   
   $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
   $uc = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential -ArgumentList $Credential.Username,$Credential.Password

   $authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$uc)
   return $authResult
}

<#
.Synopsis
    Invoke a request to the Microsoft Graph API
.DESCRIPTION
    Invoke a request to the Microsoft Graph API using the Token and setting content type to correct format (JSON)
.EXAMPLE
    $Token = Get-GraphAuthToken -AADTenant "runbookguru.onmicrosoft.com" -ClientId "cdec3c46-b1cd-4ce7-859a-b6fac1ceafee" -RedirectUri "http://www.runbook.guru" -Credential (get-credential)
    Invoke-GraphRequest -url "https://graph.microsoft.com/beta/subscriptions/303d5e85-d6c2-4c2d-9ed3-bd6b2fb5ecf1" -Token $Token -Method DELETE
.NOTES
    This is a preview/beta version. Please send any comments to jgs@coretech.dk
    Developed by MVP Jakob Gottlieb Svendsen - jakob@runbook.guru - jgs@coretech.dk
.LINK
    http://graph.microsoft.io/
#>

Function Invoke-GraphRequest {
    param($Token, $url, $Method, $Body)
    
    try {
        $headers = @{}
        $headers.Add('Authorization','Bearer ' + $Token.AccessToken)
        $headers.Add('Content-Type', "application/json")

        if($Body)
        {
           $response = Invoke-WebRequest -Uri $url -Method $Method -Body $Body -Headers $headers -UseBasicParsing
        }
        else
        {
           $response = Invoke-WebRequest -Uri $url -Method $Method -Headers $headers -UseBasicParsing
        }

        return (ConvertFrom-Json $response.Content)
    }
    catch
    {
        #throw ($error[0].Exception.Response)
        if($_.Exception.Response)
        {
            $result = $_.Exception.Response.GetResponseStream()
            $reader = New-Object System.IO.StreamReader($result)
            $responseBody = $reader.ReadToEnd();
            throw "Status: A system exception was caught.`n $responsebody"
        }
        else
        {
            throw $_
        }

    }
   
}

<#
.Synopsis
    Gets a subscription object from Microsoft Graph API
.DESCRIPTION
    Gets a subscription object from Microsoft Graph API
.EXAMPLE
    $Token = Get-GraphAuthToken -AADTenant "runbookguru.onmicrosoft.com" -ClientId "cdec3c46-b1cd-4ce7-859a-b6fac1ceafee" -RedirectUri "http://www.runbook.guru" -Credential (get-credential)
    Get-GraphSubscription -Token $Token -SubscriptionId "b539f640-7a5b-462e-960d-e7cb6a3460f6"
.NOTES
    This is a preview/beta version. Please send any comments to jgs@coretech.dk
    Developed by MVP Jakob Gottlieb Svendsen - jakob@runbook.guru - jgs@coretech.dk
.LINK
    http://graph.microsoft.io/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/resources/subscription/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/api/subscription_get/
#>

Function Get-GraphSubscription {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)] 
        [Object] $Token, 
        [Parameter(Mandatory=$true)] 
        [String] $SubscriptionId
    )
  
    $url =  "https://graph.microsoft.com/beta/subscriptions"
    $responseBody = Invoke-GraphRequest -url "https://graph.microsoft.com/beta/subscriptions/$SubscriptionId" -Token $Token -Method Get
    return $responseBody

}

<#
.Synopsis
    Creates a new subscription object in the Microsoft Graph API
.DESCRIPTION
    Creates a new subscription object in the Microsoft Graph API
.EXAMPLE
    $Token = Get-GraphAuthToken -AADTenant "runbookguru.onmicrosoft.com" -ClientId "cdec3c46-b1cd-4ce7-859a-b6fac1ceafee" -RedirectUri "http://www.runbook.guru" -Credential (get-credential)
    $webhook = "https://demo.azurewebsites.net/api/webhooks?code=dffdsfdj6pqfrldb6pghzxrihse1zm7vutbj4i&token=VYa2bgSAPCt9NoIx8%2f%2fmG2HrVMvp46vta5Zq6%2bo468Q%3d"
    $resource = "me/mailFolders('Inbox')/messages"
    New-GraphSubscription -Token $Token -ResourceUri $resource -WebhookUri $webhook -ChangeType Created,Deleted,Updated
.NOTES
This is a preview/beta version. Please send any comments to jgs@coretech.dk
Developed by MVP Jakob Gottlieb Svendsen - jakob@runbook.guru - jgs@coretech.dk
.LINK
    http://graph.microsoft.io/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/resources/subscription/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/api/subscription_post_subscriptions/
#>

Function New-GraphSubscription {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)] 
        [Object] $Token, 
        [Parameter(Mandatory=$true)] 
        [String] $ResourceUri, 
        [Parameter(Mandatory=$true)] 
        [String] $WebhookUri, 
        [ValidateSet("Created", "Updated", "Deleted")]
        [String[]] $ChangeType = "Created", 
        [DateTime] $ExpiratetionDateTime =  (get-date).ToUniversalTime().AddMinutes(4230), 
        [String] $ClientState = "DefaultClientState"
    )
  
  $url =  "https://graph.microsoft.com/beta/subscriptions"

  $FormattedDate = $ExpiratetionDateTime.ToString("yyyy-MM-ddThh:mm:ss.FFFFFFFZ")

  $Request = @"
{
   "changeType": "$($ChangeType -join ",")",
   "notificationUrl": "$WebhookUri",
   "resource": "$ResourceUri",
   "expirationDateTime":"$FormattedDate",
   "clientState": "$ClientState"
}
"@


    $responseBody = Invoke-GraphRequest -Token $Token -url $Url -Method Post -Body $Request

    return $responseBody

}


<#
.Synopsis
    Removes a subscription object from Microsoft Graph API
.DESCRIPTION
    Removes a subscription object from Microsoft Graph API
.EXAMPLE
    $Token = Get-GraphAuthToken -AADTenant "runbookguru.onmicrosoft.com" -ClientId "cdec3c46-b1cd-4ce7-859a-b6fac1ceafee" -RedirectUri "http://www.runbook.guru" -Credential (get-credential)
    Remove-GraphSubscription -Token $Token -SubscriptionId "b539f640-7a5b-462e-960d-e7cb6a3460f6"
.NOTES
    This is a preview/beta version. Please send any comments to jgs@coretech.dk
    Developed by MVP Jakob Gottlieb Svendsen - jakob@runbook.guru - jgs@coretech.dk
.LINK
    http://graph.microsoft.io/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/resources/subscription/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/api/subscription_delete/
#>

Function Remove-GraphSubscription {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)] 
        [Object] $Token, 
        [Parameter(Mandatory=$true)] 
        [String] $SubscriptionId
    )
  
    $url =  "https://graph.microsoft.com/beta/subscriptions"
    $responseBody = Invoke-GraphRequest -url "https://graph.microsoft.com/beta/subscriptions/$SubscriptionId" -Token $Token -Method DELETE
    return $responseBody

}

<#
.Synopsis
Updates a subscription object in Microsoft Graph API
.DESCRIPTION
Updates a subscription object in Microsoft Graph API
.EXAMPLE
$Token = Get-GraphAuthToken -AADTenant "runbookguru.onmicrosoft.com" -ClientId "cdec3c46-b1cd-4ce7-859a-b6fac1ceafee" -RedirectUri "http://www.runbook.guru" -Credential (get-credential)
Remove-GraphSubscription -Token $Token -SubscriptionId "b539f640-7a5b-462e-960d-e7cb6a3460f6"
.NOTES
This is a preview/beta version. Please send any comments to jgs@coretech.dk
Developed by MVP Jakob Gottlieb Svendsen - jakob@runbook.guru - jgs@coretech.dk
.LINK
    http://graph.microsoft.io/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/resources/subscription/
.LINK
    http://graph.microsoft.io/en-us/docs/api-reference/beta/api/subscription_update/
#>

Function Update-GraphSubscription {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)] 
        [object] $Token, 
        [Parameter(Mandatory=$true)] 
        [String] $SubscriptionId,
        [DateTime] $ExpiratetionDateTime = (get-date).ToUniversalTime().AddMinutes(4230)
    )
  
      $url =  "https://graph.microsoft.com/beta/subscriptions"
    $FormattedDate = $ExpiratetionDateTime.ToString("yyyy-MM-ddThh:mm:ss.FFFFFFFZ")

    
  $Request = @"
    {
       "expirationDateTime":"$FormattedDate",
    }
"@


    $responseBody = Invoke-GraphRequest -url "https://graph.microsoft.com/beta/subscriptions/$SubscriptionId" -Token $Token -Method PATCH -Body $Request
    return $responseBody

}