-
Notifications
You must be signed in to change notification settings - Fork 1
/
Win32AppRemedy.ps1
729 lines (699 loc) · 29.6 KB
/
Win32AppRemedy.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
<#
.SYNOPSIS
Win32AppRemedy - An Azure Automation Runbook - requires the following Automation Variables defined:
ClientID - The AppID of your service principal Azure AD App
ClientSecret - The ClientSecret of your service principal Azure AD App
TenantID - The AzureAD TenantID of your tenant
TeamsWebHook - The Webhook url for your Teams Reporting Channel
TeamsReporting - True or False to turn Teams Reporting on off
.DESCRIPTION
Win32AppRemedy is used to remediate updates for Win32Apps that are assigned as available by using Device Based patching groups.
These groups are dynamicly created based on devices that have the previous version installed, app is assigned as required to these groups with a deadline for install.
Teams reporting will publish a message card to a chosen teams channel.
.PARAMETER OrgAppID
Input parameter Intune AppID for the current application version
.PARAMETER UpdatedAppID
Input parameter Intune AppID for the updated application version
.PARAMETER OrgAppVersion
Input parameter - Name of the current application in Intune, Example "Adobe Acrobat Reader DC 20.009.20042"
.PARAMETER OrgAppVersion
Input parameter - Name of the updated application in Intune , Example "Adobe Acrobat Reader DC 20.009.20063"
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-03-29
Updated: 2020-03-29
Version history:
1.0.0 - (2020-05-20) Initial Version with app remediation groups
1.0.1 - (2020-06-11) Buxfix for no devices needing updates for Teams Reporting and Restartbehaviortype for App assignment.
#>
param (
[parameter(Mandatory = $true)]
$OrgAppID,
[parameter(Mandatory = $true)]
$UpdatedAppID,
[parameter(Mandatory = $true)]
$OrgAppVersion,
[parameter(Mandatory = $true)]
$UpdatedAppVersion
)
#region Initialize
#Fetching all variables from the Automation Account
$ClientID = Get-AutomationVariable -Name 'ClientID'
$ClientSecret = Get-AutomationVariable -Name 'ClientSecret'
$TenantID = Get-AutomationVariable -Name 'TenantID'
$TeamsReporting = Get-AutomationVariable -Name 'TeamsReporting'
Write-Output "Declarations done"
#endregion Initialize
#region Functions
function Get-MSGraphAppToken{
<#
.SYNOPSIS
Get app based authentication token for MS Graph and return Header for authentication.
.DESCRIPTION
Get app based authentication token for MS Graph and return Header for authentication
.PARAMETER TenantID
Azure AD Tenant ID for authentication
.PARAMETER ClientID
Azure AD App Client ID
.PARAMETER ClientSecret
Client Secret for Azure AD Authentication
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-03-29
Updated: 2020-03-29
Version history:
1.0.0 - (2020-03-29) Function created
#>
[CmdletBinding()]
param (
[parameter(Mandatory = $true, HelpMessage = "Your Azure AD Directory ID should be provided")]
[ValidateNotNullOrEmpty()]
[string]$TenantID,
[parameter(Mandatory = $true, HelpMessage = "Application ID for an Azure AD application")]
[ValidateNotNullOrEmpty()]
[string]$ClientID,
[parameter(Mandatory = $true, HelpMessage = "Azure AD Application Client Secret.")]
[ValidateNotNullOrEmpty()]
[string]$ClientSecret
)
Process {
$ErrorActionPreference = "Stop"
# Construct URI
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
# Construct Body
$body = @{
client_id = $clientId
scope = "https://graph.microsoft.com/.default"
client_secret = $clientSecret
grant_type = "client_credentials"
}
try {
$MyTokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing
$MyToken =($MyTokenRequest.Content | ConvertFrom-Json).access_token
If(!$MyToken){
Write-Warning "Failed to get Graph API access token!"
Exit 1
}
$MyHeader = @{"Authorization" = "Bearer $MyToken" }
}
catch [System.Exception] {
Write-Warning "Failed to get Access Token, Error message: $($_.Exception.Message)"; break
}
return $MyHeader
}
}#end function
function Invoke-TeamsMessage{
<#
.SYNOPSIS
Send a message card to defined teams channel webhook
.DESCRIPTION
Send a message card to defined teams channel webhook
.PARAMETER teamswebhook
Teams Channel Webhook
.PARAMETER Text
Text for message
.PARAMETER UpdateStatus
Text for UpdateStatus
.PARAMETER StatusColor
Colorcode for message
.PARAMETER DeviceName
String with devices needing a update
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-03-29
Updated: 2020-03-29
Version history:
1.0.0 - (2020-03-29) Function created
#>
param (
[Parameter(Mandatory=$true)]
$teamswebhook,
[Parameter(Mandatory=$true)]
$text,
[Parameter(Mandatory=$true)]
$UpdateStatus,
[Parameter(Mandatory=$true)]
$StatusColor,
[Parameter(Mandatory=$true)]
$DeviceName
)
$Now = Get-Date
$payload = @"
{
"@type": "MessageCard",
"@context": "https://schema.org/extensions",
"summary": "PMPC App Update Status",
"themeColor": "$StatusColor",
"title": "$UpdateStatus",
"sections": [
{
"activityTitle": "Patch My PC Status",
"activitySubtitle": "$Now",
"facts": [
{
"name": "Devices:",
"value": "$DeviceName"
}
],
"text": "$text"
}
]
}
"@
Invoke-RestMethod -uri $teamswebhook -Method Post -body $payload -ContentType 'application/json' | Out-Null
}#endfunction
function Get-IntuneWin32AppAssignment {
<#
.SYNOPSIS
Retrieve all assignments for a Win32 app.
.DESCRIPTION
Retrieve all assignments for a Win32 app.
.PARAMETER ID
Specify the ID for a Win32 application.
.PARAMETER ApplicationID
Specify the Application ID of the app registration in Azure AD. By default, the script will attempt to use well known Microsoft Intune PowerShell app registration.
.NOTES
ModifiedBy: Jan Ketil Skanke @JankeSkanke
Author: Nickolaj Andersen
Contact: @NickolajA
Created: 2020-04-29
Updated: 2020-04-29
Version history:
1.0.0 - (2020-04-29) Function created
#>
param(
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ID,
[Parameter(Mandatory=$true)]
$Header
)
try {
# Attempt to call Graph and retrieve all assignments for Win32 app
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($ID)/assignments"
$Win32AppAssignmentResponse = Invoke-RestMethod -Method "GET" -Uri $Uri -ContentType "application/json" -Headers $Header -ErrorAction Stop
if ($Win32AppAssignmentResponse.value -ne $null) {
foreach ($Win32AppAssignment in $Win32AppAssignmentResponse.value) {
Write-Verbose -Message "Successfully retrieved Win32 app assignment with ID: $($Win32AppAssignment.id)"
Write-Output -InputObject $Win32AppAssignment
}
}
}
catch [System.Exception] {
Write-Warning -Message "An error occurred while retrieving Win32 app assignments for app with ID: $($Win32AppID). Error message: $($_.Exception.Message)"
}
}#endfunction
function Add-IntuneWin32AppAssignment {
<#
.SYNOPSIS
Assign a Win32App to a Device Group
.DESCRIPTION
Assign a Win32App to a Device Group
.PARAMETER AppID
Specify the AppID for a Win32 application.
.PARAMETER GroupID
Specify the GroupID for a Win32 application assignment
.PARAMETER Nofification
Specify the Notification parameter for the assignment
.PARAMETER DeliveryOptimization
Specify the DeliveryOptimization parameter for the assignment
.PARAMETER GracePeriod
Specify the GracePeriod parameter for the assignment
.PARAMETER RestartCountDown
Specify the RestartCountDown parameter for the assignment
.PARAMETER RestartSnooze
Specify the RestartSnooze parameter for the assignment
.PARAMETER DeadlineInDays
Specify the DeadLine in Days parameter for the assignment
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-05-10
Updated: 2020-05-10
Version history:
1.0.0 - (2020-04-29) Function created
#>
param(
[Parameter(Mandatory=$true)]
$Header,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$AppID,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$GroupID,
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[ValidateSet("showAll", "showReboot", "hideAll")]
[string]$Notification = "showReboot",
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[ValidateSet("notConfigured", "foreground")]
[string]$DeliveryOptimization = "notConfigured",
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$GracePeriod = "1440",
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$RestartCountDown = "30",
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[string]$RestartSnooze = "30",
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[int32]$DeadlineInDays = "2"
)
#Define install deadline
[string]$Deadline = Get-Date((Get-Date).AddDays($DeadlineInDays)) -Format "yyyy-MM-ddTHH:mm:ssZ"
$Win32AppUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($AppID)"
$Win32App = Invoke-RestMethod -Method Get -Uri $Win32AppUri -ContentType "application/json" -Headers $Header
Write-Output "Restart behavior is set to $($Win32App.installExperience.deviceRestartBehavior)"
if (($Win32App.installExperience.deviceRestartBehavior -eq "basedOnReturnCode") -or ($Win32App.installExperience.deviceRestartBehavior -eq "force"))
{
Write-Output "Assigning app with Restart Grace"
$Win32AppAssignmentBody = [ordered]@{
"@odata.type" = "#microsoft.graph.mobileAppAssignment"
"intent" = "required"
"source" = "direct"
"target" = @{
"@odata.type" = "#microsoft.graph.groupAssignmentTarget"
"groupId" = "$GroupID"
}
"settings" = @{
"@odata.type" = "#microsoft.graph.win32LobAppAssignmentSettings"
"notifications" = "$Notification"
"deliveryOptimizationPriority" = "$DeliveryOptimization"
"restartSettings" = @{
"gracePeriodInMinutes" = "$GracePeriod"
"countdownDisplayBeforeRestartInMinutes" = "$RestartCountDown"
"restartNotificationSnoozeDurationInMinutes" = "$RestartSnooze"
}
"installTimeSettings" = @{
"useLocalTime" = $true
"startDateTime" = $null
"deadlineDateTime" = $Deadline
}
}
}
}
else{
Write-Output "Assigning app without Restart Grace, grace not applicable"
# Construct table for Win32 app assignment body
$Win32AppAssignmentBody = [ordered]@{
"@odata.type" = "#microsoft.graph.mobileAppAssignment"
"intent" = "required"
"source" = "direct"
"target" = @{
"@odata.type" = "#microsoft.graph.groupAssignmentTarget"
"groupId" = "$GroupID"
}
"settings" = @{
"@odata.type" = "#microsoft.graph.win32LobAppAssignmentSettings"
"notifications" = "$Notification"
"deliveryOptimizationPriority" = "$DeliveryOptimization"
"installTimeSettings" = @{
"useLocalTime" = $true
"startDateTime" = $null
"deadlineDateTime" = $Deadline
}
}
}
}
Write-Output ($Win32AppAssignmentBody | ConvertTo-Json)
$uri = -join ("https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/", $AppID ,"/assignments")
Write-Output $uri
try {
# Attempt to call Graph and create new assignment for Win32 app
$Win32AppAssignmentResponse = Invoke-RestMethod -Method "POST" -Uri $uri -Body ($Win32AppAssignmentBody | ConvertTo-Json) -ContentType "application/json" -Headers $Header -ErrorAction Stop
if ($Win32AppAssignmentResponse.id) {
Write-Output "Successfully created Win32 app assignment with ID: $($Win32AppAssignmentResponse.id)"
}
}
catch [System.Exception] {
Write-Warning -Message "An error occurred while creating app assignment. Error message: $($_.Exception.Message)"
}
}#endfunction
function Remove-IntuneAppAssignment{
<#
.SYNOPSIS
Remove an assignment of a Win32 app to specified AAD groupID
.DESCRIPTION
Remove an assignment of a Win32 app to specified AAD groupID
.PARAMETER AppID
Specify the ID for the Win32 application.
.PARAMETER DeviceGroupID
Specify the Group ID for Device Patching Group
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Original Author: @Nickolaja
Created: 2020-13-05
Updated: 2020-13-05
Version history:
1.0.0 Function Created
#>
param(
[Parameter(Mandatory=$true)]
$Header,
[parameter(Mandatory = $true)]
[string]$AppID,
[Parameter(Mandatory=$true)]
[string]$DeviceGroupID
)
$uri = -join ("https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/", $AppID ,"/assignments")
Write-Output $uri
try {
# Attempt to call Graph and create new assignment for Win32 app
$Win32AppAssignments = Invoke-RestMethod -Method "GET" -Uri $uri -ContentType "application/json" -Headers $Header -ErrorAction Stop
foreach ($Win32AppAssignment in $Win32AppAssignments.value){
$CurrentWin32AppAssignment = Invoke-RestMethod -Method "GET" -uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($AppID)/assignments/$($Win32AppAssignment.id)" -Headers $Header -ErrorAction Stop
If (($CurrentWin32AppAssignment.target.'@odata.type') -like "*.groupAssignmentTarget"){
if (($CurrentWin32AppAssignment.target.GroupID) -eq $DeviceGroupID){
#remove assignment
Invoke-RestMethod -uri "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($AppID)/assignments/$($CurrentWin32AppAssignment.id)" -Method "DELETE" -Headers $Header -ErrorAction Stop
}
}
}
}
catch [System.Exception] {
Write-Warning -Message "An error occurred while removing app assignment. Error message: $($_.Exception.Message)"
}
}#endfunction
function Get-DeviceAppInstallState{
<#
.SYNOPSIS
Retrieve all devices with Win32 app installed
.DESCRIPTION
Retrieve all assignments for a Win32 app.
.PARAMETER ID
Specify the ID for a Win32 application.
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-04-29
Updated: 2020-04-29
Version history:
1.0.0 - (2020-05-05) Function created
#>
param(
[Parameter(Mandatory=$true)]
$Header,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ID
)
try {
# Attempt to call Graph and retrieve all devices with app installed equals true
$uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$($ID)/deviceStatuses?filter=installState eq 'installed'&Select=deviceID"
$Win32AppDevices = Invoke-RestMethod -Method GET -Uri $Uri -ContentType "application/json" -Headers $Header -ErrorAction Stop
if ($Win32AppDevices.value -ne $null) {
foreach ($Win32AppDevice in $Win32AppDevices.value) {
Write-Output $Win32AppDevice.deviceID
}
}
}
catch [System.Exception] {
Write-Warning -Message "An error occurred while getting installstate for app with ID: $($ID). Error message: $($_.Exception.Message)"
}
}#endfunction
Function GetNameStringForIntuneSearch{
<#
.SYNOPSIS
Get Application simplified string for search via Graph Api
.DESCRIPTION
Get Application simplified string for search via Graph Api
.PARAMETER name
Specify the full name for the application
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-04-29
Updated: 2020-04-29
Version history:
1.0.0 - (2020-05-05) Function created
#>
param (
[string]$name)
if ($name -match "\d+\.\d+(\.\d+)?(\.\d+)?")
{
$result = $name.Split($Matches[0])
$result = $result[0].Trim()
return $result
}
return $name
}#endfunction
function Invoke-CreateAADGroup{
<#
.SYNOPSIS
Create AzureAD Device Group for Patch Remediation
.DESCRIPTION
Create AzureAD Device Group for Patch Remediation
.PARAMETER DisplayName
The groups Displayname in Azure AD
.PARAMETER Description
The group description on the group in Azure AD
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-04-29
Updated: 2020-04-29
Version history:
1.0.0 - (2020-05-05) Function created
#>
param (
[Parameter(Mandatory=$true)]
$Header,
[Parameter(Mandatory=$true)]
$Description,
[Parameter(Mandatory=$true)]
$DisplayName
)
$newGroupJSONObject = @{
"description" = $Description
"displayName"= $DisplayName
"mailEnabled" = $false
"mailNickname" = "none"
"securityEnabled" = $true
} | ConvertTo-Json
$Group = Invoke-RestMethod -Method POST -Uri 'https://graph.microsoft.com/beta/groups/' -ContentType "application/json" -Headers $Header -Body $newGroupJSONObject
Return $Group
}#endfunction
function Get-AADPatchingGroup{
<#
.SYNOPSIS
Get AzureAD Device Group used for Patch Remediation
.DESCRIPTION
Get AzureAD Device Group used for Patch Remediation
.PARAMETER GroupName
Name of the Group in Azure AD
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-04-29
Updated: 2020-04-29
Version history:
1.0.0 - (2020-05-05) Function created
#>
param (
[Parameter(Mandatory=$true)]
$Header,
[Parameter(Mandatory=$true)]
$GroupName
)
try {
# Attempt to call Graph and retrieve AAD Group
$uri = "https://graph.microsoft.com/beta/groups?`$filter=displayname eq '$GroupName'"
$Group = Invoke-RestMethod -Method "GET" -Uri $uri -ContentType "application/json" -Headers $Header -ErrorAction Stop
Return $Group
}
catch [System.Exception] {
Write-Warning -Message "An error occurred while retrieving Group with GroupName: $($GroupName). Error message: $($_.Exception.Message)"
}
}#endfunction
function Remove-AADPatchingGroup{
<#
.SYNOPSIS
Remove AzureAD Device Group used for Patch Remediation
.DESCRIPTION
Remove AzureAD Device Group used for Patch Remediation
.PARAMETER GroupID
The GroupID of the Group in Azure AD to remove
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-04-29
Updated: 2020-04-29
Version history:
1.0.0 - (2020-05-05) Function created
#>
param (
[Parameter(Mandatory=$true)]
$Header,
[Parameter(Mandatory=$true)]
$GroupID
)
try {
# Attempt to call Graph and Delete AAD Group
$uri = "https://graph.microsoft.com/beta/groups/$($GroupID)"
$DeleteAADGroupResponse = Invoke-RestMethod -Method "DELETE" -Uri $uri -ContentType "application/json" -Headers $Header -ErrorAction Stop
Return $DeleteAADGroupResponse
}
catch [System.Exception] {
Write-Warning -Message "An error occurred while retrieving Group with GroupName: $($GroupName). Error message: $($_.Exception.Message)"
}
}#endfunction
function Add-DeviceToAADGroup{
<#
.SYNOPSIS
Add Devices to AAD Group
.DESCRIPTION
Add Devices to AAD Group
.PARAMETER DeviceID
Specify the DeviceID to add to group
.NOTES
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-04-29
Updated: 2020-04-29
Version history:
1.0.0 - (2020-05-05) Function created
#>
param(
[Parameter(Mandatory=$true)]
$Header,
[parameter(Mandatory = $true)]
[string]$DeviceID
)
try {
#Get AzureAD Device id from ManagedDeviceID
$uri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices/$($DeviceID)?&select=azureADDeviceId"
$AADDeviceIDQuery = Invoke-RestMethod -Method Get -Uri $uri -ContentType "application/json" -Headers $Header
$AADDeviceID =$AADDeviceIDQuery.azureADDeviceId
#Get AzureAD Directory Object from AzureAD DeviceID
$DirectoryObjectUrl = -join ("https://graph.microsoft.com/beta/devices?filter=deviceId eq '",$AADDeviceID, "'&select=id")
$DirectoryObject = Invoke-RestMethod -Method Get -Uri $DirectoryObjectUrl -ContentType "application/json" -Headers $Header
$DirectoryObjectID = $DirectoryObject.value.id
$AddToGroupUri = "https://graph.microsoft.com/beta/groups/$RemediationGroupID/members/`$ref"
$Body = [ordered]@{
"@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/$DirectoryObjectID"
}
Write-Output "Adding $AADDeviceID to group $GroupName"
Invoke-RestMethod -Method Post -Uri $AddToGroupUri -Body ($Body | ConvertTo-Json) -ContentType "application/json" -Headers $Header -ErrorAction Stop
}
catch [System.Exception] {
Write-Warning -Message "An error occurred while adding device with ID: $($DeviceID) to group. Error message: $($_.Exception.Message)"
}
}#endfunction
#endregion Functions
#region Script
#Get Authentication Token for MSGraph
Try
{
$Header = Get-MSGraphAppToken -TenantID $tenantId -ClientID $ClientID -ClientSecret $ClientSecret -ErrorAction Stop
}
Catch
{
$ErrorMessage = $_.Exception.Message
Write-Error -Message "Connection to Graph failed with $ErrorMessage"
Break
}
if ($Header) {
Write-Output "Connected to Microsoft Graph"
Write-Output "Patching app $OrgAppVersion ID: $OrgAppID with $UpdatedAppVersion ID: $UpdatedAppID"
$CurrentAssignment = Get-IntuneWin32AppAssignment -ID $UPDATEDAPPID -Header $Header
#If new app is assigned as available - detect all devices with installstate = installed and add to patchinggroup
#This is based on that other mechanism handles the app update itself and assigns updated app to available and not required
if ($CurrentAssignment.intent -contains "available"){
#Detect and remove old patching group
$OldPatchingGroup = Get-AADPatchingGroup -GroupName "AppRemedy-$($ORGAPPVERSION)" -Header $Header
if ($OldPatchingGroup.value -ne $null){
Write-Output "Old Patching group found. Deleting old Patching Group and assignments"
#removing eventually copied assignement from PMPC
Write-Output "Removing App Assignement for $($OldPatchingGroup.value.id)"
Remove-IntuneAppAssignment -AppID $UPDATEDAPPID -DeviceGroupID $OldPatchingGroup.value.id -Header $Header
#removing group
Remove-AADPatchingGroup -GroupID $OldPatchingGroup.value.id -Header $Header
}
else{
Write-Output "No old Patching Group exists, continues..."
}
#Creating new patching group
Write-Output "App is assigned as available, creating patching group for remediation"
$GroupName = -join("AppRemedy-", $UPDATEDAPPVERSION)
$GroupDescription = -join("App Remediation Group for ", $UPDATEDAPPVERSION)
$RemediationGroup = Invoke-CreateAADGroup -Description $GroupDescription -DisplayName $GroupName -Header $Header
$RemediationGroupID = $RemediationGroup.id
#Detect devices with previous versions of the app and add them to the patching group
$AppSearchName = GetNameStringForIntuneSearch -name $UpdatedAppVersion
$AppSearchUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?`$filter=isof('microsoft.graph.win32LobApp')&`$search=`"$AppSearchName`"&Select=id, displayName"
$AllAppVersionsDetected = Invoke-RestMethod -Method Get -Uri $AppSearchUri -ContentType "application/json" -Headers $Header
foreach ($App in $AllAppVersionsDetected.value | Where-Object {$_.id -notmatch $UpdatedAppID}){
$CurrentAppID = $app.id
#Write-Output "CurrentAPPID $CurrentAppID"
$Devices = Get-DeviceAppInstallState -ID $CurrentAppID -Header $Header| Get-Unique
foreach ($Device in $Devices){
Add-DeviceToAADGroup -DeviceID $Device -Header $Header
}
}
}
elseif ($CurrentAssignment.intent -notcontains "available" -And $CurrentAssignment.intent -contains "required"){
Write-Output "App is already assigned as required only, no action needed"
}
#Asssigning Updated App to Patching Group as Required with a 2 day deadline
Add-IntuneWin32AppAssignment -AppID $UPDATEDAPPID -GroupID $RemediationGroupID -Notification showAll -DeliveryOptimization foreground -GracePeriod 1440 -RestartCountDown 20 -RestartSnooze 15 -DeadlineInDays 3 -Header $Header
#If Teams Reporting is set to True in Runbook Variable
if ($TeamsReporting){
$TeamsWebHook = Get-AutomationVariable -Name 'TeamsReportChannelWebHook'
#Finding app name - stripping out version for search
$AppSearchName = GetNameStringForIntuneSearch -name $UpdatedAppVersion
$AppSearchUri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?`$filter=isof('microsoft.graph.win32LobApp')&`$search=`"$AppSearchName`"&Select=id, displayName"
$AllAppVersionsDetected = Invoke-RestMethod -Method Get -Uri $AppSearchUri -ContentType "application/json" -Headers $Header
$DeviceNames =[System.Collections.ArrayList]@()
foreach ($App in $AllAppVersionsDetected.value | Where-Object {$_.id -notmatch $UpdatedAppID}){
$CurrentAppID = $app.id
$CurrentAppVersion = $app.displayName
#Write-Output $CurrentAppID
$DeviceStateOldUri = -join('https://graph.microsoft.com/beta/deviceappmanagement/mobileApps/', $CurrentAppID,'/deviceStatuses?filter=installState eq ',"'","installed","'",'&Select=deviceName, deviceID')
#Write-Output "DeviceStateOLDURI is $DeviceStateOldUri"
$QueryOldAppDeviceStatuses = Invoke-RestMethod -Method Get -Uri $DeviceStateOldUri -ContentType "application/json" -Headers $Header
$OldAppDeviceStatuses = $QueryOldAppDeviceStatuses.value.deviceName | Get-Unique
#Write-Output "Status $OldAppDeviceStatuses"
if ($OldAppDeviceStatuses.count -ne 0){
foreach ($device in $OldAppDeviceStatuses) {
$DeviceNames.Add($Device) | Out-Null
}
}
}
if (-not ([string]::IsNullOrEmpty($DeviceNames))){
$DeviceNames = $DeviceNames | Sort-Object -Unique
$StatusText = -join($DeviceNames.count, " devices needs an update to ", $UpdatedAppVersion)
$StatusColor = "FFFF00"
$Text = -join($DeviceNames.count, " devices needs an update to ", $UpdatedAppVersion)
$DeviceNameString = $null
foreach ($DeviceName in $DeviceNames) {
Write-Output "DeviceName: $DeviceName"
$DeviceNameString += " \n\n "
$DeviceNameString += $DeviceName
}
Invoke-TeamsMessage -teamswebhook $TeamsWebHook -UpdateStatus $StatusText -DeviceName $DeviceNameString -text $text -StatusColor $statuscolor| Out-Null
}
else {
$DeviceNames = "No Devices"
$StatusText = "No devices is currently using a previous version of $UpdatedAppVersion"
$StatusColor = "008000"
$Text = "No devices is currently using a previous version of $UpdatedAppVersion"
Invoke-TeamsMessage -teamswebhook $TeamsWebHook -UpdateStatus $StatusText -DeviceName $DeviceNames -text $text -StatusColor $statuscolor| Out-Null
}
}
else{
Write-Output "Teams Reporting is not enabled"
}
}
elseif (!$Header){
Write-Warning -Message "Graph Connection failed, check app secret"
Exit 1
}
#endregion Script