-
Notifications
You must be signed in to change notification settings - Fork 4
/
M365 Runbook-MUSA.ps1
2079 lines (1438 loc) · 66.7 KB
/
M365 Runbook-MUSA.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
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
##########Connect to Exchange Online##########
Write-Host -Prompt "Connecting to Exchange Online"
$credential = Get-Credential
Install-module Msonline
Import-Module MsOnline
Connect-MsolService -Credential $credential
$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $credential -Authentication "Basic" -AllowRedirection
Import-PSSession $exchangeSession -DisableNameChecking
Enable-OrganizationCustomization
############# Define CSV path of Users and Group ##################
$UserPath = Read-Host -Prompt "Enter File Path For CSV list of users"
$DistributionGroups = Read-Host -Prompt "Enter File Path For CSV list of Distro Groups"
$DistributionGroupMembers = Read-Host -Prompt "Enter File Path For CSV list of Distro Group Members"
#################Import CSV list of Users with Passwords and Assign Licenses###################################################
Import-Csv -Path $userpath | foreach {New-MsolUser -UserPrincipalName $_.UserPrincipalName -FirstName $_.FirstName -LastName $_.LastName -DisplayName $_.DisplayName -UsageLocation $_.UsageLocation -LicenseAssignment $_.LicenseAssignment -Password $_.Password -ForceChangePassword $False}
Import-Csv -Path $DistributionGroups| foreach {New-Distributiongroup -Name $_.Name -PrimarySmtpAddress $_.PrimarySmtpAddress }
################Create Encryption Rules########################
New-TransportRule -Name "Encrypt Email" -SubjectContainsWords "Encrypt" -ApplyRightsProtectionTemplate "Encrypt"
Set-IRMConfiguration -DecryptAttachmentForEncryptOnly $true
New-TransportRule -Name "Encrypt outbound sensitive emails (out of box rule)" -SentToScope NotInOrganization -ApplyRightsProtectionTemplate "Encrypt" -MessageContainsDataClassifications @(@{Name="ABA Routing Number"; minCount="1"},@{Name="Credit Card Number"; minCount="1"},@{Name="Drug Enforcement Agency (DEA) Number"; minCount="1"},@{Name="U.S. / U.K. Passport Number"; minCount="1"},@{Name="U.S. Bank Account Number"; minCount="1"},@{Name="U.S. Individual Taxpayer Identification Number (ITIN)"; minCount="1"},@{Name="U.S. Social Security Number (SSN)"; minCount="1"}) -Notifysender "NotifyOnly"
############# Setting Domain Name ##################
$DomainName = Read-Host -Prompt "Enter Tenant Domain Name"
$WhiteListURl = Read-Host -Prompt "Enter any URLs you want to whitelist. If you have none, press enter"
#########Create AIP Template to Encrypt Email and Docs on Demand#############################
Install-module AADRM
Connect-AadrmService
$AIPGroup = Read-Host -Prompt "Enter the email of the group you want to Apply AIP labels to"
$names = @{}
$names[1033] = "Encrypt1"
$descriptions = @{}
$descriptions[1033] = "Encrypt Docs and Emails"
$r1 = New-AadrmRightsDefinition -Domain $Domainname -Rights "Owner"
Add-AadrmTemplate -Names $names -Descriptions $descriptions -RightsDefinitions $r1 -ScopedIdentities $AIPGroup -Status Published
##############Creating Safe Attachments Policy ########################################
New-SafeAttachmentPolicy -Name "Policy 1" -Action Dynamicdelivery -Enable $true -ActionOnError $true
New-SafeAttachmentRule -Name "Safe Attachment Policy" -SafeAttachmentPolicy "Policy 1" -RecipientDomainIs $DomainName
###############Creating Safe Links Policy###########################
New-SafeLinksPolicy -Name "Policy 1" -DoNotTrackUserClicks $true -EnableForInternalSenders $true -DoNotAllowClickThrough $True -TrackClicks $false -ScanUrls $true -AllowClickThrough $false -DoNotRewriteUrls $WhiteListURl -IsEnabled $true
New-SafeLinksRule -Name "SafeLinksPolicy" -SafeLinksPolicy "Policy 1" -RecipientDomainIs $DomainName -Enabled $true
####################Block AutoFW######################################
$externalTransportRuleName = "Inbox Rules To External Block"
$rejectMessageText = "To improve security, auto-forwarding rules to external addresses has been disabled. Please contact your Microsoft Partner if you'd like to set up an exception."
$externalForwardRule = Get-TransportRule | Where-Object {$_.Identity -contains $externalTransportRuleName}
if (!$externalForwardRule) {
Write-Output "Client Rules To External Block not found, creating Rule"
New-TransportRule -name "Client Rules To External Block" -Priority 1 -SentToScope NotInOrganization -FromScope InOrganization -MessageTypeMatches AutoForward -RejectMessageEnhancedStatusCode 5.7.1 -RejectMessageReasonText $rejectMessageText
}
##################Set Audit Log#############################################
Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true
Write-Host "Audit Log is Enabled" -ForegroundColor Green
###############Outbound Spam###############################################
$NotifcationEntity = Read-Host -Prompt "Enter the email of the recipient who will receive the spam notifications"
Set-HostedOutboundSpamFilterPolicy Default -NotifyOutboundSpam $true -NotifyOutboundSpamRecipients $NotifcationEntity
########################Warn Users when an email arrives from a sender with the same display name as someone in your organisation#################
$ruleName = "External Senders with matching Display Names"
$ruleHtml = "<table class=MsoNormalTable border=0 cellspacing=0 cellpadding=0 align=left width=`"100%`" style='width:100.0%;mso-cellspacing:0cm;mso-yfti-tbllook:1184; mso-table-lspace:2.25pt;mso-table-rspace:2.25pt;mso-table-anchor-vertical:paragraph;mso-table-anchor-horizontal:column;mso-table-left:left;mso-padding-alt:0cm 0cm 0cm 0cm'> <tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes;mso-yfti-lastrow:yes'><td style='background:#910A19;padding:5.25pt 1.5pt 5.25pt 1.5pt'></td><td width=`"100%`" style='width:100.0%;background:#FDF2F4;padding:5.25pt 3.75pt 5.25pt 11.25pt; word-wrap:break-word' cellpadding=`"7px 5px 7px 15px`" color=`"#212121`"><div><p class=MsoNormal style='mso-element:frame;mso-element-frame-hspace:2.25pt; mso-element-wrap:around;mso-element-anchor-vertical:paragraph;mso-element-anchor-horizontal: column;mso-height-rule:exactly'><span style='font-size:9.0pt;font-family: `"Segoe UI`",sans-serif;mso-fareast-font-family:`"Times New Roman`";color:#212121'>This message was sent from outside the company by someone with a display name matching a user in your organisation. Please do not click links or open attachments unless you recognise the source of this email and know the content is safe. <o:p></o:p></span></p></div></td></tr></table>"
$rule = Get-TransportRule | Where-Object {$_.Identity -contains $ruleName}
$displayNames = (Get-Mailbox -ResultSize Unlimited).DisplayName
if (!$rule) {
Write-Host "Rule not found, creating rule" -ForegroundColor Green
New-TransportRule -Name $ruleName -Priority 0 -FromScope "NotInOrganization" -ApplyHtmlDisclaimerLocation "Prepend" `
-HeaderMatchesMessageHeader From -HeaderMatchesPatterns $displayNames -ApplyHtmlDisclaimerText $ruleHtml
}
else {
Write-Host "Rule found, updating rule" -ForegroundColor Green
Set-TransportRule -Identity $ruleName -Priority 0 -FromScope "NotInOrganization" -ApplyHtmlDisclaimerLocation "Prepend" `
-HeaderMatchesMessageHeader From -HeaderMatchesPatterns $displayNames -ApplyHtmlDisclaimerText $ruleHtml
}
################Import CSV of Groups#########################################
Import-Csv -path $DistributionGroupMembers | foreach {Add-DistributionGroupMember -Identity $_.DL -Member $_.Alias}
####################################################
function Get-AuthToken {
<#
.SYNOPSIS
This function is used to authenticate with the Graph API REST interface
.DESCRIPTION
The function authenticate with the Graph API Interface with the tenant name
.EXAMPLE
Get-AuthToken
Authenticates you with the Graph API interface
.NOTES
NAME: Get-AuthToken
#>
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true)]
$User
)
$userUpn = New-Object "System.Net.Mail.MailAddress" -ArgumentList $User
$tenant = $userUpn.Host
Write-Host "Checking for AzureAD module..."
$AadModule = Get-Module -Name "AzureAD" -ListAvailable
if ($AadModule -eq $null) {
Write-Host "AzureAD PowerShell module not found, looking for AzureADPreview"
$AadModule = Get-Module -Name "AzureADPreview" -ListAvailable
}
if ($AadModule -eq $null) {
write-host
write-host "AzureAD Powershell module not installed..." -f Red
write-host "Install by running 'Install-Module AzureAD' or 'Install-Module AzureADPreview' from an elevated PowerShell prompt" -f Yellow
write-host "Script can't continue..." -f Red
write-host
exit
}
# Getting path to ActiveDirectory Assemblies
# If the module count is greater than 1 find the latest version
if($AadModule.count -gt 1){
$Latest_Version = ($AadModule | select version | Sort-Object)[-1]
$aadModule = $AadModule | ? { $_.version -eq $Latest_Version.version }
# Checking if there are multiple versions of the same module found
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"
}
else {
$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
# https://msdn.microsoft.com/en-us/library/azure/microsoft.identitymodel.clients.activedirectory.promptbehavior.aspx
# Change the prompt behaviour to force credentials each time: Auto, Always, Never, RefreshSession
$platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"
$userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId")
$authResult = $authContext.AcquireTokenAsync($resourceAppIdURI,$clientId,$redirectUri,$platformParameters,$userId).Result
# If the accesstoken is valid then create the authentication header
if($authResult.AccessToken){
# Creating header for Authorization token
$authHeader = @{
'Content-Type'='application/json'
'Authorization'="Bearer " + $authResult.AccessToken
'ExpiresOn'=$authResult.ExpiresOn
}
return $authHeader
}
else {
Write-Host
Write-Host "Authorization Access Token is null, please re-run authentication..." -ForegroundColor Red
Write-Host
break
}
}
catch {
write-host $_.Exception.Message -f Red
write-host $_.Exception.ItemName -f Red
write-host
break
}
}
####################################################
Function Test-JSON(){
<#
.SYNOPSIS
This function is used to test if the JSON passed to a REST Post request is valid
.DESCRIPTION
The function tests if the JSON passed to the REST Post is valid
.EXAMPLE
Test-JSON -JSON $JSON
Test if the JSON is valid before calling the Graph REST interface
.NOTES
NAME: Test-JSON
#>
param (
$JSON
)
try {
$TestJSON = ConvertFrom-Json $JSON -ErrorAction Stop
$validJson = $true
}
catch {
$validJson = $false
$_.Exception
}
if (!$validJson){
Write-Host "Provided JSON isn't in valid JSON format" -f Red
break
}
}
####################################################
Function Get-itunesApplication(){
<#
.SYNOPSIS
This function is used to get an iOS application from the itunes store using the Apple REST API interface
.DESCRIPTION
The function connects to the Apple REST API Interface and returns applications from the itunes store
.EXAMPLE
Get-itunesApplication -SearchString "Microsoft Corporation"
Gets an iOS application from itunes store
.EXAMPLE
Get-itunesApplication -SearchString "Microsoft Corporation" -Limit 10
Gets an iOS application from itunes store with a limit of 10 results
.NOTES
NAME: Get-itunesApplication
#>
[cmdletbinding()]
param
(
[Parameter(Mandatory=$true)]
$SearchString,
[int]$Limit
)
try{
Write-Verbose $SearchString
# Testing if string contains a space and replacing it with a +
$SearchString = $SearchString.replace(" ","+")
Write-Verbose "SearchString variable converted if there is a space in the name $SearchString"
if($Limit){
$iTunesUrl = "https://itunes.apple.com/search?entity=software&term=$SearchString&attribute=softwareDeveloper&limit=$limit"
}
else {
$iTunesUrl = "https://itunes.apple.com/search?entity=software&term=$SearchString&attribute=softwareDeveloper"
}
write-verbose $iTunesUrl
$apps = Invoke-RestMethod -Uri $iTunesUrl -Method Get
# Putting sleep in so that no more than 20 API calls to itunes API
sleep 3
return $apps
}
catch {
write-host $_.Exception.Message -f Red
write-host $_.Exception.ItemName -f Red
write-verbose $_.Exception
write-host
break
}
}
####################################################
Function Add-iOSApplication(){
<#
.SYNOPSIS
This function is used to add an iOS application using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds an iOS application from the itunes store
.EXAMPLE
Add-iOSApplication -AuthHeader $AuthHeader
Adds an iOS application into Intune from itunes store
.NOTES
NAME: Add-iOSApplication
#>
[cmdletbinding()]
param
(
$itunesApp
)
$graphApiVersion = "Beta"
$Resource = "deviceAppManagement/mobileApps"
try {
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
$app = $itunesApp
Write-Verbose $app
Write-Host "Publishing $($app.trackName)" -f Yellow
# Step 1 - Downloading the icon for the application
$iconUrl = $app.artworkUrl60
if ($iconUrl -eq $null){
Write-Host "60x60 icon not found, using 100x100 icon"
$iconUrl = $app.artworkUrl100
}
if ($iconUrl -eq $null){
Write-Host "60x60 icon not found, using 512x512 icon"
$iconUrl = $app.artworkUrl512
}
$iconResponse = Invoke-WebRequest $iconUrl
$base64icon = [System.Convert]::ToBase64String($iconResponse.Content)
$iconType = $iconResponse.Headers["Content-Type"]
if(($app.minimumOsVersion.Split(".")).Count -gt 2){
$Split = $app.minimumOsVersion.Split(".")
$MOV = $Split[0] + "." + $Split[1]
$osVersion = [Convert]::ToDouble($MOV)
}
else {
$osVersion = [Convert]::ToDouble($app.minimumOsVersion)
}
# Setting support Operating System Devices
if($app.supportedDevices -match "iPadMini"){ $iPad = $true } else { $iPad = $false }
if($app.supportedDevices -match "iPhone6"){ $iPhone = $true } else { $iPhone = $false }
# Step 2 - Create the Hashtable Object of the application
$description = $app.description -replace "[^\x00-\x7F]+",""
$graphApp = @{
"@odata.type"="#microsoft.graph.iosStoreApp";
displayName=$app.trackName;
publisher=$app.artistName;
description=$description;
largeIcon= @{
type=$iconType;
value=$base64icon;
};
isFeatured=$false;
appStoreUrl=$app.trackViewUrl;
applicableDeviceType=@{
iPad=$iPad;
iPhoneAndIPod=$iPhone;
};
minimumSupportedOperatingSystem=@{
v8_0=$osVersion -lt 9.0;
v9_0=$osVersion -eq 9.0;
v10_0=$osVersion -gt 9.0;
};
};
$JSON2 = ConvertTo-Json $graphApp
# Step 3 - Publish the application to Graph
Write-Host "Creating application via Graph"
$createResult = Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Body (ConvertTo-Json $graphApp) -Headers $authToken
Write-Host "Application created as $uri/$($createResult.id)"
write-host
return $createResult
}
catch {
$ex = $_.Exception
Write-Host "Request to $Uri failed with HTTP Status $([int]$ex.Response.StatusCode) $($ex.Response.StatusDescription)" -f Red
$errorResponse = $ex.Response.GetResponseStream()
$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 Add-ApplicationAssignment(){
<#
.SYNOPSIS
This function is used to add an application assignment using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds a application assignment
.EXAMPLE
Add-ApplicationAssignment -ApplicationId $ApplicationId -TargetGroupId $TargetGroupId -InstallIntent $InstallIntent
Adds an application assignment in Intune
.NOTES
NAME: Add-ApplicationAssignment
#>
[cmdletbinding()]
param
(
$ApplicationId,
$TargetGroupId,
$InstallIntent
)
$graphApiVersion = "Beta"
$Resource = "deviceAppManagement/mobileApps/$ApplicationId/assign"
try {
if(!$ApplicationId){
write-host "No Application Id specified, specify a valid Application Id" -f Red
break
}
if(!$TargetGroupId){
write-host "No Target Group Id specified, specify a valid Target Group Id" -f Red
break
}
if(!$InstallIntent){
write-host "No Install Intent specified, specify a valid Install Intent - available, notApplicable, required, uninstall, availableWithoutEnrollment" -f Red
break
}
$JSON2 = @"
{
"mobileAppAssignments": [
{
"@odata.type": "#microsoft.graph.mobileAppAssignment",
"target": {
"@odata.type": "#microsoft.graph.groupAssignmentTarget",
"groupId": "$TargetGroupId"
},
"intent": "$InstallIntent"
}
]
}
"@
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON2 -ContentType "application/json"
}
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 Add-TermsAndConditions(){
<#
.SYNOPSIS
This function is used to add Terms and Conditions using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds Terms and Conditions Statement
.EXAMPLE
Add-TermsAndConditions -JSON $JSON
Adds Terms and Conditions into Intune
.NOTES
NAME: Add-TermsAndConditions
#>
[cmdletbinding()]
param
(
$JSON
)
$graphApiVersion = "Beta"
$Resource = "deviceManagement/termsAndConditions"
try {
if($JSON -eq "" -or $JSON -eq $null){
write-host "No JSON specified, please specify valid JSON for the Android Policy..." -f Red
}
else {
Test-JSON -JSON $JSON
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON -ContentType "application/json"
}
}
catch {
Write-Host
$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 Add-TermsAndConditions(){
<#
.SYNOPSIS
This function is used to add Terms and Conditions using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds Terms and Conditions Statement
.EXAMPLE
Add-TermsAndConditions -JSON $JSON
Adds Terms and Conditions into Intune
.NOTES
NAME: Add-TermsAndConditions
#>
[cmdletbinding()]
param
(
$JSON
)
$graphApiVersion = "Beta"
$Resource = "deviceManagement/termsAndConditions"
try {
if($JSON -eq "" -or $JSON -eq $null){
write-host "No JSON specified, please specify valid JSON for the Android Policy..." -f Red
}
else {
Test-JSON -JSON $JSON
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON -ContentType "application/json"
}
}
catch {
Write-Host
$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 Assign-TermsAndConditions(){
<#
.SYNOPSIS
This function is used to assign Terms and Conditions from Intune to a Group using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and assigns terms and conditions to a group
.EXAMPLE
Assign-TermsAndConditions -id $id -TargetGroupId
.NOTES
NAME: Assign-TermsAndConditions
#>
[cmdletbinding()]
param
(
$id,
$TargetGroupId
)
$graphApiVersion = "Beta"
$Resource = "deviceManagement/termsAndConditions/$id/groupAssignments"
try {
if(!$id){
Write-Host "No Terms and Conditions ID was passed to the function, specify a valid terms and conditions ID" -ForegroundColor Red
Write-Host
break
}
if(!$TargetGroupId){
write-host "No Target Group Id specified, specify a valid Target Group Id" -f Red
Write-Host
break
}
else {
$JSON = @"
{
"targetGroupId":"$TargetGroupId"
}
"@
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON -ContentType "application/json"
}
}
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 Add-MDMApplication(){
<#
.SYNOPSIS
This function is used to add an MDM application using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds an MDM application from the itunes store
.EXAMPLE
Add-MDMApplication -JSON $JSON1
Adds an application into Intune
.NOTES
NAME: Add-MDMApplication
#>
[cmdletbinding()]
param
(
$JSON1
)
$graphApiVersion = "Beta"
$App_resource = "deviceAppManagement/mobileApps"
try {
if(!$JSON1){
write-host "No JSON was passed to the function, provide a JSON variable" -f Red
break
}
Test-JSON -JSON $JSON1
$uri = "https://graph.microsoft.com/$graphApiVersion/$($App_resource)"
Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Body $JSON1 -Headers $authToken
}
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 Add-ApplicationAssignment(){
<#
.SYNOPSIS
This function is used to add an application assignment using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds a application assignment
.EXAMPLE
Add-ApplicationAssignment -ApplicationId $ApplicationId -TargetGroupId $TargetGroupId -InstallIntent $InstallIntent
Adds an application assignment in Intune
.NOTES
NAME: Add-ApplicationAssignment
#>
[cmdletbinding()]
param
(
$ApplicationId,
$TargetGroupId,
$InstallIntent
)
$graphApiVersion = "Beta"
$Resource = "deviceAppManagement/mobileApps/$ApplicationId/assign"
try {
if(!$ApplicationId){
write-host "No Application Id specified, specify a valid Application Id" -f Red
break
}
if(!$TargetGroupId){
write-host "No Target Group Id specified, specify a valid Target Group Id" -f Red
break
}
if(!$InstallIntent){
write-host "No Install Intent specified, specify a valid Install Intent - available, notApplicable, required, uninstall, availableWithoutEnrollment" -f Red
break
}
$JSON1 = @"
{
"mobileAppAssignments": [
{
"@odata.type": "#microsoft.graph.mobileAppAssignment",
"target": {
"@odata.type": "#microsoft.graph.groupAssignmentTarget",
"groupId": "$TargetGroupId"
},
"intent": "$InstallIntent"
}
]
}
"@
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON1 -ContentType "application/json"
}
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 Add-DeviceCompliancePolicy(){
<#
.SYNOPSIS
This function is used to add a device compliance policy using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds a device compliance policy
.EXAMPLE
Add-DeviceCompliancePolicy -JSON $JSON
Adds an Android device compliance policy in Intune
.NOTES
NAME: Add-DeviceCompliancePolicy
#>
[cmdletbinding()]
param
(
$JSON
)
$graphApiVersion = "v1.0"
$Resource = "deviceManagement/deviceCompliancePolicies"
try {
if($JSON -eq "" -or $JSON -eq $null){
write-host "No JSON specified, please specify valid JSON for the Android Policy..." -f Red
}
else {
Test-JSON -JSON $JSON
$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)"
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Post -Body $JSON -ContentType "application/json"