-
Notifications
You must be signed in to change notification settings - Fork 0
/
MSGraphAPI.psm1
461 lines (337 loc) · 12 KB
/
MSGraphAPI.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<#
.Synopsis
Helps leverage the Microsoft Graph API using PowerShell
.Description
Facilitates making Graph API requests using PoweShell
.Parameter Start
The first month to display.
.Parameter End
The last month to display.
.Parameter FirstDayOfWeek
The day of the month on which the week begins.
.Parameter HighlightDay
Specific days (numbered) to highlight. Used for date ranges like (25..31).
Date ranges are specified by the Windows PowerShell range syntax. These dates are
enclosed in square brackets.
.Parameter HighlightDate
Specific days (named) to highlight. These dates are surrounded by asterisks.
.Example
# Show a default display of this month.
Show-Calendar
.Example
# Display a date range.
Show-Calendar -Start "March, 2010" -End "May, 2010"
.Example
# Highlight a range of days.
Show-Calendar -HighlightDay (1..10 + 22) -HighlightDate "December 25, 2008"
#>
#Requires -version 5.0
#region Global_Construct
#
$script:SessionToken = $null
$script:SessionExpiry = $null
$script:gSessionTenant = $null
$script:gApplicationID = $null
$script:gAppSecret = $null
$script:gAPIVersion = 'v1.0'
#endregion Global_Construct
#Testing TO BE DELETED
$script:gSessionTenant = 'generatione.onmicrosoft.com' #"70def4a1-688c-4890-9d1c-3f854ac0ba68"
$script:gApplicationID = 'bf09db13-cbf5-48c1-b720-7c5de5ca7373'
$script:gAppSecret = '9XXwXnga8vKd1UH3W.OV-M6Lu3i~r~_9H4'
<############################################# Public Functions #############################################>
#region Set-APIVersion
#
function Set-APIVersion(){
param(
[Parameter(Mandatory=$true)][string] $Version
)
If(($Version -eq '1.0') -or ($Version -eq 'beta')){
#Set the API Version to be used in this session
If($Version -ne 'beta'){$Version = ('v{0}' -f $Version)}
$script:gAPIVersion = $Version
}else{
Write-Host 'ERROR: Version is incorrect please use 1.0 or beta' -ForegroundColor Red
}
}#endregion Set-APIVersion
#region Get-APIVersion
#
function Get-APIVersion(){
#Return the API version to be used in this session
return $script:gAPIVersion
}#endregion Get-APIVersion
#region Set-TenantID
#
function Set-TenantID(){
param(
[Parameter(Mandatory=$true)][string] $aTenantID
)
#Set the Tenant Name/ID to be used in this session
$script:gSessionTenant = $aTenantID
}#endregion Set-TenantID
#region Get-TenantID
#
function Get-TenantID(){
#Return the Tenant Name/ID used in this session
return $script:gSessionTenant
}#endregion Get-TenantID
#region Set-ApplicationID
#
function Set-ApplicationID(){
param(
[Parameter(Mandatory=$true)][string] $aApplicationID
)
#Set the Azure Application ID to be used in this session
$script:gApplicationID = $aApplicationID
}#endregion Set-ApplicationID
#region Get-ApplicationID
#
function Get-ApplicationID(){
#Return the Azure Application ID used in this session
return $script:gApplicationID
}#endregion Get-ApplicationID
#region Set-ApplicationSecret
#
function Set-ApplicationSecret(){
param(
[Parameter(Mandatory=$true)][string] $aAppSecret
)
#Set the Application Secret to be used in this session
$script:gAppSecret = $aAppSecret
}#endregion Set-ApplicationSecret
#region Get-ApplicationSecret
#
function Get-ApplicationSecret(){
#Return the Application Secret used in this session
return $script:gAppSecret
}#endregion Get-ApplicationSecret
<############################################# Internal Functions #############################################>
#region Request-Token
# TODO: Add verification for the token life
#
function Request-Token(){
If($script:SessionToken -eq $null){
If($script:gSessionTenant -eq $null){
Write-Host 'ERROR: A TenantID must be set using Set-TenantID before getting a Session OAUTH Token' -ForegroundColor Red
return $false
}
If($script:gApplicationID -eq $null){
Write-Host 'ERROR: An Application ID must be set using Set-ApplicationID before getting a Session OAUTH Token' -ForegroundColor Red
return $false
}
If($script:gAppSecret -eq $null){
write-Host 'ERROR: An Application Secret must be set using Set-ApplicationSecret before getting a Session OAUTH Token' -ForegroundColor Red
return $false
}
#Construct URI to login to Microsoft API
$theURI = ('https://login.microsoftonline.com/{0}/oauth2/v2.0/token' -f $script:gSessionTenant)
#Construct Body
$theBody = @{
client_id = $script:gApplicationID
scope = 'https://graph.microsoft.com/.default'
client_secret = $script:gAppSecret
grant_type = 'client_credentials'
}
#Get OAuth 2.0 Token
$theRequest = Invoke-WebRequest -Method Post -Uri $theURI -ContentType 'application/x-www-form-urlencoded' -Body $theBody -UseBasicParsing
#Return Access Token
If($theRequest.statusCode -eq '200'){
#Get Session Token
$script:SessionToken = ($theRequest.Content | ConvertFrom-Json).access_token
#Get TOken Epxiry Time
$aTokenData = $script:SessionToken.Split('.')[1].Replace('-', '+').Replace('_', '/').Replace('\n\r','')
$aUnixTime = ([System.Text.Encoding]::UTF8.GetString([convert]::FromBase64String($aTokenData))|Convertfrom-Json).exp
$Script:SessionExpiry = [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($aUnixTime))
return $true
}else{
Write-Host ("ERROR: Couldn't retrieve token, StatusCode {0} returned" -f $theRequest.statusCode) -ForegroundColor Red
return $false
end
}
}else{
If($Script:SessionExpiry -gt (Get-Date)){
return $true
}else{
#Session Expired
$Script:SessionToken = $null
$Script:SessionExpiry = $null
return (Request-Token)
}
}
}#endregion Request-Token
#region Get-APIMethod
# Run GET Method
#
function Get-APIMethod() {
Param(
[Parameter(Mandatory=$true ,ValueFromPipeline=$true)][String]$aURI,
[Parameter(Mandatory=$false,ValueFromPipeline=$false)][String]$aLimit,
[Parameter(Mandatory=$false,ValueFromPipeline=$false)][AllowNull()][String]$aFolder
)
#Initialize Variables
$theResults = [Collections.ArrayList]::new()
$theJSON = $null
#Construct the URI to call
$theURI = ('https://graph.microsoft.com/{0}/{1}' -f $script:gAPIVersion,$aURI)
#Add limits
if($aLimit){
$theURI = $theURI.replace('?',('?$top={0}&' -f $aLimit))
}
#Write Debugging output of the URI to be called
write-debug ("URI: {0}" -f $theURI)
#Check if the token is valid
if(Request-Token){
do{ #a loop to get all results
#Initialize variables
$theReturnValue = $null
$theJSON = $null
$theReturnValue = Invoke-WebRequest -Method Get -Uri $theURI -ContentType 'application/json' -Headers @{Authorization = "Bearer $script:SessionToken"} -ErrorAction Stop
<#
try{ #Running the Graph API query
$theReturnValue = Invoke-WebRequest -Method Get -Uri $theURI -ContentType 'application/json' -Headers @{Authorization = "Bearer $script:SessionToken"} -ErrorAction Stop
} catch {
Write-Host ('ERROR: GET-APIMethod failed with a StatusCode {0} and message with message {1}' -f $Error[0].Exception.Response.statusCode, $Error[0].Exception.Message) -ForegroundColor Red
return $null
end
}
#>
#Add content to results
$theJSON = ($theReturnValue.content |ConvertFrom-Json)
$theResults += $theJSON.value
#Check if there is more data to read
If($theJSON."@odata.nextlink"){$theUri = $theJSON."@odata.nextlink"}else{$theURI = $null}
#Check if we have reached the limit
If($aLimit){
If($theResults.count -ge $aLimit){$theURI = $null}
}
} until (-not $theURI)
}
#Write Results to Folder
If($aFolder){
# Write Results
If(Test-Path -Path $aFolder){
foreach ($aResult in $theResults.value){
$aResult | ConvertTo-Json -depth 100 | Out-File -FilePath ('{0}\{1}.json' -f ($aFolder), $aResult.DisplayName)
}
}else{
Write-Host -ForegroundColor Red ('ERROR: Path not found {0}' -f ($aFolder))
}
}
return $theResults
}
#endregion Get-APIMethod
<############################################# Graph Functions #############################################>
#region Get-GraphUsers
#
function Get-GraphUsers(){
Param(
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][switch]$Count = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Limit,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Select,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Filter,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Folder
)
#Setup URI & Command
$theURI = ("users?`$select={0}&`$filter={1}" -f $Select,$Filter)
$GetAPIMethod = "Get-APIMethod -aURI `$theURI"
#Add Limit
If($Limit){
$GetAPIMethod += " -aLimit `$Limit"
}
#Add Folder
If($Folder){
$GetAPIMethod += " -aFolder `$Folder"
}
#Get User Info
$Output = Invoke-Expression $GetAPIMethod
#Return requested output
If($Count){
return $Output.count
}else{
return $Output
}
}#endregion Get-GraphUsers
#region Get-GraphDeviceConfigs
#
function Get-GraphDeviceConfigs(){
Param(
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][switch]$Count = $false,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$Limit,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Select,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Folder
)
#Setup URI & Command
$theURI = ("deviceManagement/deviceConfigurations?`$select={0}&`$filter={1}" -f $Select,$Filter)
$GetAPIMethod = "Get-APIMethod -aURI `$theURI"
#Add Limit
If($Limit){
$GetAPIMethod += " -aLimit `$Limit"
}
#Add Folder
If($Folder){
$GetAPIMethod += " -aFolder `$Folder"
}
#Get Device Configurations
$Output = Invoke-Expression $GetAPIMethod
#Return requested output
If($Count){
return $Output.count
}else{
return $Output
}
}#endregion Get-GraphDeviceConfigs
#region Get-GraphAIPPolicies
#
function Get-GraphAIPPolicies(){
Param(
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$Limit = '100',
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Folder
)
#Get AIP POlicies
$theURI = ("deviceAppManagement/windowsInformationProtectionPolicies?`$top={0}" -f $Limit)
If($Folder){Get-APIMethod $theURI, $Folder}else{Get-APIMethod $theURI}
}#endregion Get-GraphAIPPolicies
#region Get-GraphAPI
#
function Get-GraphAPI(){
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$false)][string]$URI,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$Limit,
[Parameter(Mandatory=$false, ValueFromPipeline=$false)][AllowNull()][String]$Folder
)
#Setup URI
$theURI = ("{0}" -f $URI)
#Setup Command
$GetAPIMethod = "Get-APIMethod -aURI `$theURI"
#Add Limit
If($Limit){
$GetAPIMethod += " -aLimit `$Limit"
}
#Add Folder
If($Folder){
$GetAPIMethod += " -aFolder `$Folder"
}
#Get User Info
$Output = Invoke-Expression $GetAPIMethod
#Return requested output
If($Count){
return $Output.count
}else{
return $Output
}
}#endregion Get-GraphAPI
<############################################# Export Functions #############################################>
#Sets & Gets
Export-ModuleMember -Function Set-APIVersion
Export-ModuleMember -Function Get-APIVersion
Export-ModuleMember -Function Set-TenantID
Export-ModuleMember -Function Get-TenantID
Export-ModuleMember -Function Set-ApplicationID
Export-ModuleMember -Function Get-ApplicationID
Export-ModuleMember -Function Set-ApplicationSecret
Export-ModuleMember -Function Get-ApplicationSecret
#Functions for Graph
Export-ModuleMember -Function Get-GraphUsers
Export-ModuleMember -Function Get-GraphDeviceConfigs
Export-ModuleMember -Function Get-GraphAIPPolicies
Export-ModuleMember -Function Get-GraphAPI