forked from ThomasKur/IntuneDocumentation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocumentIntune.ps1
More file actions
1223 lines (1051 loc) · 46.8 KB
/
DocumentIntune.ps1
File metadata and controls
1223 lines (1051 loc) · 46.8 KB
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.DESCRIPTION
This Script documents an Intune Tenand with almostb all settings, which are available over the Graph API.
The Script is using the PSWord and AzureAD Module. Therefore you have to install them first.
.EXAMPLE
.NOTES
Author: Thomas Kurth/baseVISION
Co-Author: jflieben
Date: 4.7.2018
History
001: First Version
002: SetRegistryKey Function now allows to set empty values
003: Change CreateFolder Function to first create folder and then write the log. Otherwise whe function can fail, when the logfile folder doesn't exist.
004: Improved Log Action
005: Version is now taken from Variable, Log can be written to Windows Event,
ScriptName does no longer contain Script FileName, which is now available in $CurrentFileName
006: ScriptPath not allways read correctly. Sometimes it was a relative path.
007: Better formating and Option to specify the Save As location
008: Jos Lieben: Fixed a few things and added Conditional Access Policies
009: Thomas Kurth: Adding AutoPilot Information
ExitCodes:
99001: Could not Write to LogFile
99002: Could not Write to Windows Log
99003: Could not Set ExitMessageRegistry
#>
[CmdletBinding()]
Param()
## Manual Variable Definition
########################################################
$DebugPreference = "Continue"
$ScriptVersion = "008"
$ScriptName = "DocumentIntune"
$LogFilePathFolder = Join-Path -Path $Env:TEMP -ChildPath $ScriptName
# Log Configuration
$DefaultLogOutputMode = "Console" # "Console-LogFile","Console-WindowsEvent","LogFile-WindowsEvent","Console","LogFile","WindowsEvent","All"
$DefaultLogWindowsEventSource = $ScriptName
$DefaultLogWindowsEventLog = "CustomPS"
$MaxStringLengthSettings = 350
$DocumentName = "DocumentIntune.docx"
$DateTimeRegex = "\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z"
#region Functions
########################################################
function Write-Log {
<#
.DESCRIPTION
Write text to a logfile with the current time.
.PARAMETER Message
Specifies the message to log.
.PARAMETER Type
Type of Message ("Info","Debug","Warn","Error").
.PARAMETER OutputMode
Specifies where the log should be written. Possible values are "Console","LogFile" and "Both".
.PARAMETER Exception
You can write an exception object to the log file if there was an exception.
.EXAMPLE
Write-Log -Message "Start process XY"
.NOTES
This function should be used to log information to console or log file.
#>
param(
[Parameter(Mandatory=$true,Position=1)]
[String]
$Message
,
[Parameter(Mandatory=$false)]
[ValidateSet("Info","Debug","Warn","Error")]
[String]
$Type = "Debug"
,
[Parameter(Mandatory=$false)]
[ValidateSet("Console-LogFile","Console-WindowsEvent","LogFile-WindowsEvent","Console","LogFile","WindowsEvent","All")]
[String]
$OutputMode = $DefaultLogOutputMode
,
[Parameter(Mandatory=$false)]
[Exception]
$Exception
)
$DateTimeString = Get-Date -Format "yyyy-MM-dd HH:mm:sszz"
$Output = ($DateTimeString + "`t" + $Type.ToUpper() + "`t" + $Message)
if($Exception){
$ExceptionString = ("[" + $Exception.GetType().FullName + "] " + $Exception.Message)
$Output = "$Output - $ExceptionString"
}
if ($OutputMode -eq "Console" -OR $OutputMode -eq "Console-LogFile" -OR $OutputMode -eq "Console-WindowsEvent" -OR $OutputMode -eq "All") {
if($Type -eq "Error"){
Write-Error $output
} elseif($Type -eq "Warn"){
Write-Warning $output
} elseif($Type -eq "Debug"){
Write-Debug $output
} else{
Write-Verbose $output -Verbose
}
}
if ($OutputMode -eq "LogFile" -OR $OutputMode -eq "Console-LogFile" -OR $OutputMode -eq "LogFile-WindowsEvent" -OR $OutputMode -eq "All") {
try {
Add-Content $LogFilePath -Value $Output -ErrorAction Stop
} catch {
exit 99001
}
}
if ($OutputMode -eq "Console-WindowsEvent" -OR $OutputMode -eq "WindowsEvent" -OR $OutputMode -eq "LogFile-WindowsEvent" -OR $OutputMode -eq "All") {
try {
New-EventLog -LogName $DefaultLogWindowsEventLog -Source $DefaultLogWindowsEventSource -ErrorAction SilentlyContinue
switch ($Type) {
"Warn" {
$EventType = "Warning"
break
}
"Error" {
$EventType = "Error"
break
}
default {
$EventType = "Information"
}
}
Write-EventLog -LogName $DefaultLogWindowsEventLog -Source $DefaultLogWindowsEventSource -EntryType $EventType -EventId 1 -Message $Output -ErrorAction Stop
} catch {
exit 99002
}
}
}
function New-Folder{
<#
.DESCRIPTION
Creates a Folder if it's not existing.
.PARAMETER Path
Specifies the path of the new folder.
.EXAMPLE
CreateFolder "c:\temp"
.NOTES
This function creates a folder if doesn't exist.
#>
param(
[Parameter(Mandatory=$True,Position=1)]
[string]$Path
)
# Check if the folder Exists
if (Test-Path $Path) {
Write-Log "Folder: $Path Already Exists"
} else {
New-Item -Path $Path -type directory | Out-Null
Write-Log "Creating $Path"
}
}
function get-graphTokenForIntune(){
<#
.SYNOPSIS
Retrieve special graph token to interact with the beta (and normal) Intune endpoint
.DESCRIPTION
this function wil also, if needed, register the well known microsoft ID for intune PS management
.EXAMPLE
$token = get-graphTokenForIntune -Username you@domain.com -Password Welcome01
.PARAMETER Username
the UPN of a user with global admin permissions
.PARAMETER Password
Password of Username
.NOTES
author: Jos Lieben
blog: www.lieben.nu
created: 12/6/2018
requires: get-azureRMtoken.ps1
#>
Param(
[Parameter(Mandatory=$true)]$User,
[Parameter(Mandatory=$true)]$Password
)
$userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User
$tenant = $userUpn.Host
$AadModule = Get-Module -Name "AzureAD" -ListAvailable
if ($AadModule -eq $null) {$AadModule = Get-Module -Name "AzureADPreview" -ListAvailable}
if ($AadModule -eq $null) {
write-error "AzureAD Powershell module not installed...install this module into your automation account (add from the gallery) and rerun this runbook" -erroraction Continue
Throw
}
if($AadModule.count -gt 1){
$Latest_Version = ($AadModule | select version | Sort-Object)[-1]
$aadModule = $AadModule | ? { $_.version -eq $Latest_Version.version }
if($AadModule.count -gt 1){$aadModule = $AadModule | select -Unique}
}
$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
$clientId = "d1ddf0e4-d672-4dae-b554-9d5bdfd93547"
$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$resourceAppIdURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$Tenant"
try {
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"
$userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId")
$userCredentials = new-object Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential -ArgumentList $userUpn,$Password
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceAppIdURI, $clientid, $userCredentials);
if($authResult.Exception -and $authResult.Exception.ToString() -like "*Send an interactive authorization request*"){
try{
#Intune Powershell has not yet been authorized, let's try to do this on the fly;
$apiToken = get-azureRMToken -Username $User -Password $Password
$header = @{
'Authorization' = 'Bearer ' + $apiToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
$url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/d1ddf0e4-d672-4dae-b554-9d5bdfd93547/Consent?onBehalfOfAll=true" #this is the Microsoft Intune Powershell app ID managed by Microsoft
Invoke-RestMethod -Uri $url -Headers $header -Method POST -ErrorAction Stop
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceAppIdURI, $clientid, $userCredentials);
}catch{
Throw "You have not yet authorized Powershell, visit https://login.microsoftonline.com/$Tenant/oauth2/authorize?client_id=d1ddf0e4-d672-4dae-b554-9d5bdfd93547&response_type=code&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_mode=query&resource=https%3A%2F%2Fgraph.microsoft.com%2F&state=12345&prompt=admin_consent using a global administrator"
}
}
$authResult = $authResult.Result
if(!$authResult.AccessToken){
Throw "access token is null!"
}else{
return $authResult.AccessToken
}
}catch {
write-error "Failed to retrieve access token from Azure" -erroraction Continue
write-error $_ -erroraction Stop
}
}
Function Get-IntuneApplication(){
<#
.SYNOPSIS
This function is used to get applications from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets any applications added
.EXAMPLE
Get-IntuneApplication
Returns any applications configured in Intune
.NOTES
NAME: Get-IntuneApplication
#>
[cmdletbinding()]
param
(
$Name
)
$graphApiVersion = "Beta"
$Resource = "deviceAppManagement/mobileApps"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
if($Name){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { ($_.'displayName').contains("$Name") -and (!($_.'@odata.type').Contains("managed")) -and (!($_.'@odata.type').Contains("#microsoft.graph.iosVppApp")) }
} else {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { (!($_.'@odata.type').Contains("managed")) -and (!($_.'@odata.type').Contains("#microsoft.graph.iosVppApp")) }
}
} catch {
$ex = $_.Exception
Write-Log "Request to $Uri failed with HTTP Status $([int]$ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-ApplicationAssignment(){
<#
.SYNOPSIS
This function is used to get an application assignment from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets an application assignment
.EXAMPLE
Get-ApplicationAssignment
Returns an Application Assignment configured in Intune
.NOTES
NAME: Get-ApplicationAssignment
#>
[cmdletbinding()]
param
(
$ApplicationId
)
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
$graphApiVersion = "Beta"
$Resource = "deviceAppManagement/mobileApps/$ApplicationId/?`$expand=categories,assignments&_=1530020353167"
try {
if(!$ApplicationId){
write-Log "No Application Id specified, specify a valid Application Id" -Type Error
break
} else {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Assignments
}
}
catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Host "Response content:`n$responseBody" -f Red
Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
write-host
break
}
}
Function Get-AADGroup(){
<#
.SYNOPSIS
This function is used to get AAD Groups from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets any Groups registered with AAD
.EXAMPLE
Get-AADGroup
Returns all users registered with Azure AD
.NOTES
NAME: Get-AADGroup
#>
[cmdletbinding()]
param
(
$GroupName,
$id,
[switch]$Members
)
# Defining Variables
$graphApiVersion = "v1.0"
$Group_resource = "groups"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
if($id){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)?`$filter=id eq '$id'"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} elseif($GroupName -eq "" -or $GroupName -eq $null){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} else {
if(!$Members){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)?`$filter=displayname eq '$GroupName'"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} elseif($Members){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)?`$filter=displayname eq '$GroupName'"
$Group = (Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
if($Group){
$GID = $Group.id
$Group.displayName
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)/$GID/Members"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
}
}
}
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-DeviceCompliancePolicy(){
<#
.SYNOPSIS
This function is used to get device compliance policies from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets any device compliance policies
.EXAMPLE
Get-DeviceCompliancePolicy
Returns any device compliance policies configured in Intune
.EXAMPLE
Get-DeviceCompliancePolicy -Android
Returns any device compliance policies for Android configured in Intune
.EXAMPLE
Get-DeviceCompliancePolicy -iOS
Returns any device compliance policies for iOS configured in Intune
.NOTES
NAME: Get-DeviceCompliancePolicy
#>
[cmdletbinding()]
param
(
$Name,
[switch]$Android,
[switch]$iOS,
[switch]$Win10
)
$graphApiVersion = "Beta"
$Resource = "deviceManagement/deviceCompliancePolicies"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
$Count_Params = 0
if($Android.IsPresent){ $Count_Params++ }
if($iOS.IsPresent){ $Count_Params++ }
if($Win10.IsPresent){ $Count_Params++ }
if($Name.IsPresent){ $Count_Params++ }
if($Count_Params -gt 1){
write-Log "Multiple parameters set, specify a single parameter -Android -iOS or -Win10 against the function" -Type Error
} elseif($Android){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { ($_.'@odata.type').contains("android") }
} elseif($iOS){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { ($_.'@odata.type').contains("ios") }
} elseif($Win10){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { ($_.'@odata.type').contains("windows10CompliancePolicy") }
} elseif($Name){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { ($_.'displayName').contains("$Name") }
} else {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
}
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-AADUserDetails(){
Param(
$userGuid
)
$header = @{
'Authorization' = 'Bearer ' + $rmToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
$url = "https://main.iam.ad.ext.azure.com/api/UserDetails/$userGuid"
Write-Output (Invoke-RestMethod -Uri $url -Headers $header -Method GET -ErrorAction Stop)
}
Function Get-DeviceCompliancePolicyAssignment(){
<#
.SYNOPSIS
This function is used to get device compliance policy assignment from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets a device compliance policy assignment
.EXAMPLE
Get-DeviceCompliancePolicyAssignment -id $id
Returns any device compliance policy assignment configured in Intune
.NOTES
NAME: Get-DeviceCompliancePolicyAssignment
#>
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true,HelpMessage="Enter id (guid) for the Device Compliance Policy you want to check assignment")]
$id
)
$graphApiVersion = "Beta"
$DCP_resource = "deviceManagement/deviceCompliancePolicies"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)/$id/assignments"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-TermsAndConditions(){
<#
.SYNOPSIS
This function is used to get the Get Terms And Conditions intune resource from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets the Terms and Conditions Intune Resource
.EXAMPLE
Get-TermsAndConditions
Returns the Organization resource configured in Intune
.NOTES
NAME: Get-TermsAndConditions
#>
[cmdletbinding()]
param
(
$Name
)
$graphApiVersion = "Beta"
$resource = "deviceManagement/termsAndConditions"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
if($Name){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { ($_.'displayName').contains("$Name") }
} else {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
}
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-DeviceEnrollmentRestrictions(){
<#
.SYNOPSIS
This function is used to get device enrollment restrictions resource from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets the device enrollment restrictions Resource
.EXAMPLE
Get-DeviceEnrollmentRestrictions -id $id
Returns device enrollment restrictions configured in Intune
.NOTES
NAME: Get-DeviceEnrollmentRestrictions
#>
[cmdletbinding()]
param
(
$id
)
$graphApiVersion = "Beta"
$Resource = "deviceManagement/deviceEnrollmentConfigurations"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Host "Response content:`n$responseBody" -f Red
Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
}
}
Function Get-Organization(){
<#
.SYNOPSIS
This function is used to get the Organization intune resource from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets the Organization Intune Resource
.EXAMPLE
Get-Organization
Returns the Organization resource configured in Intune
.NOTES
NAME: Get-Organization
#>
[cmdletbinding()]
$graphApiVersion = "Beta"
$resource = "organization"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-DeviceConfigurationPolicy(){
<#
.SYNOPSIS
This function is used to get device configuration policies from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets any device configuration policies
.EXAMPLE
Get-DeviceConfigurationPolicy
Returns any device configuration policies configured in Intune
.NOTES
NAME: Get-DeviceConfigurationPolicy
#>
[cmdletbinding()]
param
(
$name
)
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
$graphApiVersion = "Beta"
$DCP_resource = "deviceManagement/deviceConfigurations"
try {
if($Name){
$uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value | Where-Object { ($_.'displayName').contains("$Name") }
} else {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
}
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-DeviceConfigurationPolicyAssignment(){
<#
.SYNOPSIS
This function is used to get device configuration policy assignment from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets a device configuration policy assignment
.EXAMPLE
Get-DeviceConfigurationPolicyAssignment $id guid
Returns any device configuration policy assignment configured in Intune
.NOTES
NAME: Get-DeviceConfigurationPolicyAssignment
#>
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true,HelpMessage="Enter id (guid) for the Device Configuration Policy you want to check assignment")]
$id
)
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
$graphApiVersion = "Beta"
$DCP_resource = "deviceManagement/deviceConfigurations"
try {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)/$id/assignments"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
Function Get-WindowsAutopilotConfig(){
<#
.SYNOPSIS
This function is used to get the AutoPilot configuration from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets the AutoPilot Configuration
.EXAMPLE
Get-WindowsAutopilotConfig
Returns the AutoPilot Configuration configured in Intune
.NOTES
NAME: Get-WindowsAutopilotConfig
#>
[cmdletbinding()]
$graphApiVersion = "Beta"
$resource = "deviceManagement/windowsAutopilotDeploymentProfiles"
$graphHeader = @{
'Authorization' = 'Bearer ' + $authToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
try {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($resource)"
(Invoke-RestMethod -Uri $uri -Headers $graphHeader -Method Get).Value
} catch {
$ex = $_.Exception
$errorResponse = $ex.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($errorResponse)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd();
Write-Log "Response content:`n$responseBody" -Type Error
Write-Log "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" -Type Error
}
}
function get-azureRMToken(){
<#
.SYNOPSIS
Retrieve special Azure RM token to use for the main.iam.ad.ext.azure.com endpoint
.DESCRIPTION
The Azure RM token can be used for various actions that are not possible using Powershell cmdlets. This is experimental and should be used with caution!
.EXAMPLE
$token = get-azureRMToken -Username you@domain.com -Password Welcome01
.PARAMETER Username
the UPN of a user with sufficient permissions to call the endpoint (this depends on what you'll use the token for)
.PARAMETER Password
Password of Username
.NOTES
filename: get-azureRMToken.ps1
author: Jos Lieben
blog: www.lieben.nu
created: 12/6/2018
#>
Param(
[Parameter(Mandatory=$true)]$Username,
[Parameter(Mandatory=$true)]$Password
)
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($Username, $secpasswd)
$res = login-azurermaccount -Credential $mycreds
$context = Get-AzureRmContext
$tenantId = $context.Tenant.Id
$refreshToken = @($context.TokenCache.ReadItems() | where {$_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date)})[0].RefreshToken
$body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
$apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
return $apiToken.access_token
}
function get-conditionalAccessPolicySettings(){
<#
.SYNOPSIS
Retrieve conditional access policy settings from Intune
.DESCRIPTION
Retrieves all conditional access policies from Intune (if policyId is omitted) and outputs their settings
.EXAMPLE
$policies = get-conditionalAccessPolicySettings
.EXAMPLE
$policy = get-conditionalAccessPolicySettings -policyId 533ceb01-3603-48cb-8586-56a60153939d
.PARAMETER policyId
GUID of the policy you wish to return, if left empty, all policies will be returned
.NOTES
filename: get-conditionalAccessPolicySettings.ps1
author: Jos Lieben
blog: www.lieben.nu
created: 12/6/2018
requires: global azure rm token
#>
Param(
$policyId #if not specified, return all policies
)
$header = @{
'Authorization' = 'Bearer ' + $rmToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()}
if(!$policyId){
$url = "https://main.iam.ad.ext.azure.com/api/Policies/Policies?top=100&nextLink=null&appId=&includeBaseline=true"
$policies = @(Invoke-RestMethod -Uri $url -Headers $header -Method GET -ErrorAction Stop).items
foreach($policy in $policies){
get-conditionalAccessPolicySettings -Username $Username -Password $Password -policyId $policy.policyId
}
}else{
$url = "https://main.iam.ad.ext.azure.com/api/Policies/$policyId"
try{
$policy = Invoke-RestMethod -Uri $url -Headers $header -Method GET -ErrorAction Stop
Write-Output $policy
}catch{}
}
}
Function Format-MsGraphData(){
<#
.SYNOPSIS
This function CLeansup Values Returned By Microsoft Graph
.DESCRIPTION
This function CLeansup Values Returned By Microsoft Graph
.EXAMPLE
Format-MsGraphData -Value "@Odata.Type"
Returns "Type"
.NOTES
NAME: Format-MsGraphData
#>
[cmdletbinding()]
param
(
[Parameter(Mandatory=$false)]
[AllowEmptyString()]
[AllowNull()]
[String]$Value
)
$Value = $Value -replace "#microsoft.graph.",""
$Value = $Value -replace "windows","win"
$Value = $Value -replace "StoreforBusiness","SfB"
$Value = $Value -replace "@odata.",""
if($Value -ne $null -and $Value -match "@{*"){
$Value = $Value -replace "@{",""
$Value = $Value -replace "}",""
$Value = $Value -replace ";",""
}
if($Value -match $DateTimeRegex){
try{
[DateTime]$Date = ([DateTime]::Parse($Value))
$Value = "$($Date.ToShortDateString()) $($Date.ToShortTimeString())"
} catch {
}
}
return $value
}
#endregion
#region Dynamic Variables and Parameters
########################################################
$LogFilePath = "$LogFilePathFolder\{0}_{1}_{2}.log" -f ($ScriptName -replace ".ps1", ''),$ScriptVersion,(Get-Date -uformat %Y%m%d%H%M)
#endregion
#region Initialization
########################################################
New-Folder $LogFilePathFolder
Write-Log "Start Script $Scriptname"
#region Loading Modules
Write-Log "Checking for AzureAD module..."
$AadModule = Get-Module -Name "AzureAD" -ListAvailable
if ($AadModule -eq $null) {
Write-Log "AzureAD PowerShell module not found, looking for AzureADPreview"
$AadModule = Get-Module -Name "AzureADPreview" -ListAvailable
}
if ($AadModule -eq $null) {
write-Log "AzureAD Powershell module not installed..." -Type Warn
write-Log "Install by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt" -Type Warn
write-Log "Script can't continue..." -Type Warn
exit
}
Write-Log "Checking for PSWord module..."
$PSWordModule = Get-Module -Name "PSWord" -ListAvailable
if ($PSWordModule -eq $null) {
write-Log "PSWord Powershell module not installed..." -Type Warn
write-Log "Install by running 'Install-Module PSWord' from an elevated PowerShell prompt" -Type Warn
write-Log "Script can't continue..." -Type Warn
exit
}
#endregion
#region Authentication
$credentials = Get-Credential -Message "Please enter Office 365 / Azure global admin credentials"
$user = $credentials.GetNetworkCredential().UserName
$password = $credentials.GetNetworkCredential().Password
$Global:authToken = get-graphTokenForIntune -User $user -Password $password
$Global:rmToken = get-azureRMToken -Username $user -Password $password
#endregion
#endregion
#region Main Script
########################################################
#region Save Path
try{