-
Notifications
You must be signed in to change notification settings - Fork 7
/
Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.ps1
852 lines (773 loc) · 44.1 KB
/
Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.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
###
# Parameters Used By Script
###
Param (
[Parameter(Mandatory=$TRUE, ValueFromPipeline=$TRUE, ValueFromPipelineByPropertyName=$TRUE,
HelpMessage='Please specify the FQDN of the AAD Tenant to target')]
[ValidateNotNullOrEmpty()]
[string]$aadTenantFQDN,
[Parameter(Mandatory=$TRUE, ValueFromPipeline=$TRUE, ValueFromPipelineByPropertyName=$TRUE,
HelpMessage='Please specify the name of the Application Registration')]
[ValidateNotNullOrEmpty()]
[string]$appRegDisplayName,
[string]$customLifetimeSecretInDays,
[switch]$createOrUpdateApp,
[switch]$deleteApp,
[switch]$updateAPIPerms,
[switch]$createClientSecret,
[switch]$deleteAllClientSecrets,
[switch]$listAllClientSecrets
)
###
# Version Of Script
###
$version = "v0.8, 2024-06-28"
<#
AUTHOR
Written By....................: Jorge de Almeida Pinto
Re-Written By.................: N.A.
Company.......................: SEMPERIS [https://www.semperis.com/]
DISCLAIMER
- The script is FREEWARE, you are free to distribute/update it, but always refer to this website (https://github.com/Semperis/) as the location where you got it
- This script is furnished "AS IS". NO warranty is expressed or implied!
- I/We HAVE NOT tested it in every scenario or environment
- ALWAYS TEST FIRST in lab environment to see if it meets your needs!
- Use this script at YOUR OWN RISK! YOU ARE RESPONSIBLE FOR ANY OUTCOME/RESULT BY USING THIS SCRIPT!
- I/We DO NOT warrant this script to be fit for any purpose, use or environment!
- I/We have tried to check everything that needed to be checked, but I/We DO NOT guarantee the script does not have bugs!
- I/We DO NOT guarantee the script will not damage or destroy your system(s), environment or anything else due to improper use or bugs!
- I/We DO NOT accept liability in any way when making mistakes, use the script wrong or in any other way where damage is caused to your environment/systems!
- If you do not accept these terms DO NOT use the script in any way and delete it immediately!
TODO
- N.A.
KNOWN ISSUES/BUGS
- The script does not check for the correct combination of parameters
- If using v2.0.0 of the Microsoft.Graph PoSH module, there is an assembly conflict with Az.Accounts that breaks authentication. The solution is to install v2.1.0 of the Microsoft.Graph PoSH module.
Also see: https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/2161
RELEASE NOTES
v0.8, 2024-06-28, Jorge de Almeida Pinto [MVP-EMS]:
- Added the MSFT Graph roles "GroupMember.Read.All", "RoleEligibilitySchedule.Read.Directory" to the list of MSFT Graph required roles
- Removed the MSFT Graph roles "Group.Read.All" from the list of MSFT Graph required roles
v0.7, 2023-07-29, Jorge de Almeida Pinto [MVP-EMS]:
- Remove the "-ForceRefresh" parameter from the CMDlet "Connect-MgGraph" as it was not available anymore in newer Microsoft.Graph PoSH modules
- Updated the way to connect to Azure AD
- If the parameter 'updateAPIPerms' is used, the Connect-AzAccount is used first through username/password and if applicable MFA, then an access token is retrieved for MSGRAPH to use with Connect-MgGraph
- If the parameter 'updateAPIPerms' is NOT used, the Connect-MgGraph is used through username/password and if applicable MFA
- Changed order of importing the PowerShell module for Az.Accounts and Microsoft.Graph. If the Azure Accounts PowerShell Module is imported AFTER importing the Microsoft Graph PowerShell Module, the following
error occurs when executing Connect-AzAccount:
Method not found: 'System.Threading.Tasks.Task`1<Azure.Identity.AuthenticationRecord> Azure.Identity.InteractiveBrowserCredential.AuthenticateAsync(Azure.Core.TokenRequestContext, System.Threading.CancellationToken)'.
- Some minor updates in the code when checking for null/empty values
v0.6, 2023-06-27, Jorge de Almeida Pinto [MVP-EMS]:
- Added the MSFT Graph roles "Device.Read.All" to the list of MSFT Graph required roles
v0.5, 2023-06-06, Jorge de Almeida Pinto [MVP-EMS]:
- When running just the script without any parameter, it will display where information can be retrieved to use the script
- Small textual updates
- Moved to start using the Microsoft Graph PowerShell modules as Azure AD And Azure AD Preview PowerShell modules are planned for deprecation
- https://learn.microsoft.com/en-us/powershell/microsoftgraph/migration-steps?
- https://learn.microsoft.com/en-us/powershell/microsoftgraph/azuread-msoline-cmdlet-map
- Now also displays the command line that was used when executing the script
- Added the parameter to list all existing client secrets
v0.4, 2022-11-21, Jorge de Almeida Pinto [MVP-EMS]:
- Added the MSFT Graph roles "AuditLog.Read.All" to the list of MSFT Graph required roles
v0.3, 2022-10-20, Jorge de Almeida Pinto [MVP-EMS]:
- Fixed the name of the variable, after community feedback (Submitted by 'aps-support', THANK YOU!)
- Changed the structure of the script for easier maintenance and to match other scripts
- Moved the definition of MSFT Graph required roles into its own section for easier maintenance and better visibility
- Added the MSFT Graph roles "RoleManagement.Read.All" and "UserAuthenticationMethod.Read.All" to the list of MSFT Graph required roles
- Updated the logic, added try/catch, to give a nicer error when the initial authentication fails with either Connect-AzureAD or Connect-AzAccount
v0.2, 2022-07-01, Jorge de Almeida Pinto [MVP-EMS]:
- Added a default timer of 1 hour for the secret
- Added the ability to provide a custom lifetime in days
- Added a parameter to delete all the secrets present
- Some code improvements
v0.1, 2022-06-24, Jorge de Almeida Pinto [MVP-EMS]:
- Initial version of the script
#>
<#
.SYNOPSIS
This PoSH Script Creates The App Registration In AAD For PK To Be Able To Scan For Vulnerabilities In AAD
.DESCRIPTION
This PoSH script provides the following functions:
- Create and update the app registration in AAD for PK To Be Able To Scan For Vulnerabilities In AAD
- Delete the app registration in AAD
- Assign the following MSFT Graph Application Permissions and consent those, when either creating or updating the app
(https://docs.purple-knight.com/community/purpleknight/pk-create-configure-app-registration.htm?tocpath=Purple%20Knight%7CPurple%20Knight%20User%20Guide%7CGetting%20Started%7C_____3)
- AdministrativeUnit.Read.All
- Application.Read.All
- AuditLog.Read.All
- Device.Read.All
- Directory.Read.All
- GroupMember.Read.All
- Policy.Read.All
- PrivilegedAccess.Read.AzureAD
- Reports.Read.All
- RoleEligibilitySchedule.Read.Directory
- RoleManagement.Read.All
- RoleManagement.Read.Directory
- User.Read.All
- UserAuthenticationMethod.Read.All
- Create an client secret that by default is valid for an hour, when either creating or updating the app. If needed it is possible to provide a customer lifetime in days for the client secret. This is not recommended as it may be a security issue
- Deleting all client secrets from the app registration in AAD
- Display the tenant ID, the application ID, the assigned and consented permissions, and the client secret to be used in the Purple Knight executable
.PARAMETER aadTenantFQDN
With This Parameter, You Can Specify The Tenant FQDN To Target The AAD Tenant To create The App Registration In
.PARAMETER appRegDisplayName
With This Parameter, You Can Specify The Name For The Application Registration
.PARAMETER customLifetimeSecretInDays
With This Parameter, You Can Specify The Custom Lifetime Of The Client Secret In Days
.PARAMETER createOrUpdateApp
With This Parameter, You Can Specify To Either Create A New App Registration Or Update An Existing App Registration
.PARAMETER deleteApp
With This Parameter, You Can Specify To Delete An Existing App Registration
.PARAMETER updateAPIPerms
With This Parameter, You Can Specify To Update The API Permissions When Either Creating A New App Registration Or Updating An Existing App Registration
.PARAMETER createClientSecret
With This Parameter, You Can Specify To Create A New Client Client Secret When Either Creating A New App Registration Or Updating An Existing App Registration
.PARAMETER deleteAllClientSecrets
With This Parameter, You Can Specify To Delete All Existing Client Secrets Whether Those Are Expired Or Not (Only When App Already Exists!)
.PARAMETER listAllClientSecrets
With This Parameter, You Can Specify To List All Existing Client Secrets (Only When App Already Exists!)
.EXAMPLE
Create A Purple Knight Vulnerability Scanning App In AAD OR Update The Purple Knight Vulnerability Scanning App In AAD With Updated API Permissions And A New Client Secret (Existing Client Secrets WILL NOT Be Deleted!)
.\Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.ps1 -aadTenantFQDN XXX.ONMICROSOFT.COM -appRegDisplayName "Semperis Purple Knight Vulnerability Scanning App" -createOrUpdateApp -updateAPIPerms -createClientSecret
.EXAMPLE
Update An Existing Purple Knight Vulnerability Scanning App In AAD With Updated API Permissions
.\Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.ps1 -aadTenantFQDN XXX.ONMICROSOFT.COM -appRegDisplayName "Semperis Purple Knight Vulnerability Scanning App" -createOrUpdateApp -updateAPIPerms
.EXAMPLE
Update An Existing Purple Knight Vulnerability Scanning App In AAD With A New Client Secret (Existing Client Secrets WILL NOT Be Deleted!)
.\Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.ps1 -aadTenantFQDN XXX.ONMICROSOFT.COM -appRegDisplayName "Semperis Purple Knight Vulnerability Scanning App" -createOrUpdateApp -createClientSecret
.EXAMPLE
List All Existing Client Secrets On The Existing Purple Knight Vulnerability Scanning App In AAD
.\Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.ps1 -aadTenantFQDN XXX.ONMICROSOFT.COM -appRegDisplayName "Semperis Purple Knight Vulnerability Scanning App" -listAllClientSecrets
.EXAMPLE
Delete All Existing Client Secrets On The Existing Purple Knight Vulnerability Scanning App In AAD
.\Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.ps1 -aadTenantFQDN XXX.ONMICROSOFT.COM -appRegDisplayName "Semperis Purple Knight Vulnerability Scanning App" -createOrUpdateApp -deleteAllClientSecrets
.EXAMPLE
Delete An Existing Purple Knight Vulnerability Scanning App In AAD
.\Create-Update-Delete-AAD-PK-Vulnerability-Scanning-App.ps1 -aadTenantFQDN XXX.ONMICROSOFT.COM -appRegDisplayName "Semperis Purple Knight Vulnerability Scanning App" -deleteApp
.NOTES
- Requires Microsoft Graph PoSH Module to connect to Azure AD and perform all actions, except consenting API permissions
- Requires Az.Accounts PoSH Module to be able to consent the API permissions
- To create, configure AND consent application permissions for the Microsoft Graph, at least membership of the "Global Administrator" built-in role is required
- To create and configure (without assigning and consenting application permissions for the Microsoft Graph), at least membership of the "Application Administrator" or "Cloud Application Administrator" built-in role is required
- To create a new client secret, at least application ownership is required of the existing application
- To UnInstall All Microsoft.Graph Modules, execute:
Uninstall-Module Microsoft.Graph -AllVersions
Get-InstalledModule Microsoft.Graph.* | ForEach-Object { if($_.Name -ne "Microsoft.Graph.Authentication") {
Uninstall-Module $_.Name -AllVersions}
}
Uninstall-Module Microsoft.Graph.Authentication -AllVersions
#>
###
# Functions Used In Script
###
# FUNCTION: Retrieve The Tenant ID From The Tenant FQDN
Function retrieveTenantIDFromTenantFQDN () {
Param (
[Parameter(Mandatory=$TRUE, ValueFromPipeline=$TRUE, ValueFromPipelineByPropertyName=$TRUE,
HelpMessage='Please specify the AAD Tenant FQDN')]
[ValidateNotNullOrEmpty()]
$tenantFQDN
)
# Specify The Tenant Specific Discovery Endpoint URL
$oidcConfigDiscoveryURL = $null
$oidcConfigDiscoveryURL = "https://login.microsoftonline.com/$tenantFQDN/v2.0/.well-known/openid-configuration"
$oidcConfigDiscoveryResult = $null
# Retrieve The Information From The Discovery Endpoint URL
$tenantId = $null
$oidcConfigDiscoveryResult = $null
Try {
$oidcConfigDiscoveryResult = Invoke-RestMethod -Uri $oidcConfigDiscoveryURL -ErrorAction Stop
} Catch {
Write-Host ""
Write-Host "Failed To Retrieve The Information From The Discovery Endpoint URL..." -ForegroundColor Red
Write-Host ""
}
# If There Is A Result Determine The Tenant ID
If ($null -ne $oidcConfigDiscoveryResult) {
$tenantId = $oidcConfigDiscoveryResult.authorization_endpoint.Split("/")[3]
}
Return $tenantId
}
###
# Clear The Screen
###
Clear-Host
###
# Configure The Appropriate Screen And Buffer Size To Make Sure Everything Fits Nicely
###
$uiConfig = (Get-Host).UI.RawUI
$uiConfig.WindowTitle = "+++ CREATE/UPDATE/DELETE PURPLE KNIGHT VULNERABILITY SCANNING APP IN AAD +++"
$uiConfig.ForegroundColor = "Yellow"
$uiConfigBufferSize = $uiConfig.BufferSize
$uiConfigBufferSize.Width = 200
$uiConfigBufferSize.Height = 9999
$uiConfigScreenSizeMax = $uiConfig.MaxPhysicalWindowSize
$uiConfigScreenSizeMaxWidth = $uiConfigScreenSizeMax.Width
$uiConfigScreenSizeMaxHeight = $uiConfigScreenSizeMax.Height
$uiConfigScreenSize = $uiConfig.WindowSize
If ($uiConfigScreenSizeMaxWidth -lt 200) {
$uiConfigScreenSize.Width = $uiConfigScreenSizeMaxWidth
} Else {
$uiConfigScreenSize.Width = 200
}
If ($uiConfigScreenSizeMaxHeight -lt 50) {
$uiConfigScreenSize.Height = $uiConfigScreenSizeMaxHeight - 5
} Else {
$uiConfigScreenSize.Height = 50
}
$uiConfig.BufferSize = $uiConfigBufferSize
$uiConfig.WindowSize = $uiConfigScreenSize
###
# Definition Of Some Constants
###
$execDateTime = Get-Date
$startDateTime = $execDateTime.ToString("yyyy-MM-dd HH:mm:ss")
$scriptFullPath = $MyInvocation.MyCommand.Definition
$scriptCmdLineUsed = $MyInvocation.Line
$scriptFolderPath = Split-Path $scriptFullPath
$currentScriptName = Split-Path $scriptFullPath -Leaf
$scriptParameterListUsed = $PSBoundParameters
$argsCount = $PSBoundParameters.Count
$userAccount = [Security.Principal.WindowsIdentity]::GetCurrent()
$localComputerName = $(Get-WmiObject -Class Win32_ComputerSystem).Name
$fqdnADDomainOfComputer = $(Get-WmiObject -Class Win32_ComputerSystem).Domain
$fqdnOfComputer = $localComputerName + "." + $fqdnADDomainOfComputer
$msftGraphListOfRequiredPermissions = @()
$msftGraphListOfRequiredPermissions += "AdministrativeUnit.Read.All"
$msftGraphListOfRequiredPermissions += "Application.Read.All"
$msftGraphListOfRequiredPermissions += "AuditLog.Read.All"
$msftGraphListOfRequiredPermissions += "Device.Read.All"
$msftGraphListOfRequiredPermissions += "Directory.Read.All"
$msftGraphListOfRequiredPermissions += "GroupMember.Read.All"
$msftGraphListOfRequiredPermissions += "Policy.Read.All"
$msftGraphListOfRequiredPermissions += "PrivilegedAccess.Read.AzureAD"
$msftGraphListOfRequiredPermissions += "Reports.Read.All"
$msftGraphListOfRequiredPermissions += "RoleEligibilitySchedule.Read.Directory"
$msftGraphListOfRequiredPermissions += "RoleManagement.Read.All"
$msftGraphListOfRequiredPermissions += "RoleManagement.Read.Directory"
$msftGraphListOfRequiredPermissions += "User.Read.All"
$msftGraphListOfRequiredPermissions += "UserAuthenticationMethod.Read.All"
###
# Loading Any Applicable Libraries
###
# N.A.
###
# Execute Any Additional Actions Required For The Script To Run Successfully
###
# N.A.
###
# Start Of Script
###
# Presentation Of Script Header
Write-Host ""
Write-Host " *******************************************************************************" -ForeGroundColor Magenta
Write-Host " * *" -ForeGroundColor Magenta
Write-Host " *--> Create/Update/Delete Purple Knight Vulnerability Scanning App In AAD <-- *" -ForeGroundColor Magenta
Write-Host " * *" -ForeGroundColor Magenta
Write-Host " * Written By: Jorge de Almeida Pinto *" -ForeGroundColor Magenta
Write-Host " * SEMPERIS *" -ForeGroundColor Magenta
Write-Host " * *" -ForeGroundColor Magenta
Write-Host " * $version *" -ForeGroundColor Magenta
Write-Host " * *" -ForeGroundColor Magenta
Write-Host " *******************************************************************************" -ForeGroundColor Magenta
Write-Host ""
Write-Host " __________ .__ ____ __. .__ .__ __" -ForeGroundColor Magenta
Write-Host " \______ \__ _______________ | | ____ | |/ _| ____ |__| ____ | |___/ |" -ForeGroundColor Magenta
Write-Host " | ___/ | \_ __ \____ \| | _/ __ \ | < / \| |/ ___\| | \ __\" -ForeGroundColor Magenta
Write-Host " | | | | /| | \/ |_> > |_\ ___/ | | \| | \ / /_/ > Y \ |" -ForeGroundColor Magenta
Write-Host " |____| |____/ |__| | __/|____/\___ > |____|__ \___| /__\___ /|___| /__|" -ForeGroundColor Magenta
Write-Host " |__| \/ \/ \/ /_____/ \/" -ForeGroundColor Magenta
Write-Host " ____ ____ .__ ___. .__.__ .__ __ _________ .__ _____" -ForeGroundColor Magenta
Write-Host " \ \ / /_ __| | ____ ________________ \_ |__ |__| | |__|/ |_ ___.__. / _____/ ____ _____ ____ ____ |__| ____ ____ / _ \ ______ ______" -ForeGroundColor Magenta
Write-Host " \ Y / | \ | / \_/ __ \_ __ \__ \ | __ \| | | | \ __< | | \_____ \_/ ___\\__ \ / \ / \| |/ \ / ___\ / /_\ \\____ \\____ \" -ForeGroundColor Magenta
Write-Host " \ /| | / |_| | \ ___/| | \// __ \| \_\ \ | |_| || | \___ | / \ \___ / __ \| | \ | \ | | \/ /_/ > / | \ |_> > |_> >" -ForeGroundColor Magenta
Write-Host " \___/ |____/|____/___| /\___ >__| (____ /___ /__|____/__||__| / ____| /_______ /\___ >____ /___| /___| /__|___| /\___ / \____|__ / __/| __/" -ForeGroundColor Magenta
Write-Host " \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \//_____/ \/|__| |__|" -ForeGroundColor Magenta
###
# SECTION: SCRIPT DETAILS
###
Write-Host ""
Write-Host "Current Date & Time.................: $startDateTime"
Write-Host "Run By..............................: $($userAccount.Name)"
Write-Host "Run On Machine......................: $fqdnOfComputer"
Write-Host ""
Write-Host "Script Full Path....................: $scriptFullPath"
Write-Host "Script Folder Path..................: $scriptFolderPath"
Write-Host "Script Command Line Used............: $scriptCmdLineUsed"
Write-Host ""
###
# Checking If Required Parameters Have Been Specified
###
If ($scriptParameterListUsed.Keys -notcontains "createOrUpdateApp" -And $scriptParameterListUsed.Keys -notcontains "deleteApp" -And $scriptParameterListUsed.Keys -notcontains "updateAPIPerms" -And $scriptParameterListUsed.Keys -notcontains "createClientSecret" -And $scriptParameterListUsed.Keys -notcontains "deleteAllClientSecrets" -And $scriptParameterListUsed.Keys -notcontains "listAllClientSecrets") {
Write-Host ""
Write-Host "No Parameters Were Used To Actually Tell The Script WHAT To Do." -Foregroundcolor Red
Write-Host ""
Write-Host "Available Parameters..." -Foregroundcolor Red
Get-Help .\$currentScriptName -Full
Write-Host ""
Write-Host "Please Visit 'https://github.com/Semperis/PK-AADAppReg/' To Learn More About Using The Script." -Foregroundcolor Red
Write-Host ""
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
BREAK
}
###
# Loading Azure Accounts PowerShell Module
###
If ($updateAPIPerms) {
$azAccountsModule = Get-Module -Name "Az.Accounts" -ListAvailable
If ([String]::IsNullOrEmpty($azAccountsModule)) {
Write-Host ""
Write-Host "The Azure Accounts PowerShell Module IS NOT Installed" -ForegroundColor Red
Write-Host ""
Write-Host " => The Azure Accounts PowerShell Module Can Be Installed From An Elevated PowerShell Command Prompt By Running" -ForegroundColor Red
Write-Host " - 'Install-Module Az.Accounts'" -ForegroundColor Red
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
BREAK
}
If ($azAccountsModule.count -gt 1) {
$latestVersionAzAccountsModule = ($azAccountsModule | Select-Object version | Sort-Object)[-1]
$azAccountsModule = $azAccountsModule | Where-Object {$_.version -eq $latestVersionAzAccountsModule.version}
}
Import-Module $azAccountsModule
}
###
# Loading Microsoft Graph PowerShell Module
###
$msftGraphModule = Get-Module -Name "Microsoft.Graph.Applications" -ListAvailable
If ([String]::IsNullOrEmpty($msftGraphModule)) {
Write-Host ""
Write-Host "The Microsoft Graph (Applications) PowerShell Module IS NOT Installed" -ForegroundColor Red
Write-Host ""
Write-Host " => The Microsoft Graph PowerShell Module Can Be Installed From An Elevated PowerShell Command Prompt By Running Either" -ForegroundColor Red
Write-Host " - 'Install-Module Microsoft.Graph.Applications'" -ForegroundColor Red
Write-Host " OR" -ForegroundColor Red
Write-Host " - 'Install-Module Microsoft.Graph'" -ForegroundColor Red
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
BREAK
}
If ($msftGraphModule.count -gt 1) {
$latestVersionMSFTGraphModule = ($msftGraphModule | Select-Object version | Sort-Object)[-1]
$msftGraphModule = $msftGraphModule | Where-Object {$_.version -eq $latestVersionMSFTGraphModule.version}
}
Import-Module $msftGraphModule
###
# Getting AAD Tenant Details
###
$aadTenantID = retrieveTenantIDFromTenantFQDN $aadTenantFQDN
If (!$([guid]::TryParse($aadTenantID, $([ref][guid]::Empty)))) {
Write-Host ""
Write-Host "Specified Tenant '$aadTenantFQDN' DOES NOT Exist..." -ForegroundColor Red
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
BREAK
}
###
# Connecting To Azure AD Tenant
###
$accessToken = $null
If ($updateAPIPerms) {
Write-Host "### Connecting To Azure AD Tenant '$aadTenantFQDN' ($aadTenantID) (Connect-AzAccount)..." -ForegroundColor Cyan
Write-Host ""
Try {
Connect-AzAccount -Tenant $aadTenantID -Force -ErrorAction Stop | Out-Null
$accessToken = (Get-AzAccessToken -Tenant $aadTenantID -ResourceTypeName MSGraph -ErrorAction Stop).token
} Catch {
Write-Host ""
Write-Host "Connecting And Authenticating To The Azure AD Tenant '$aadTenantFQDN' Failed (Connect-AzAccount)..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
Write-Host ""
Try {
Remove-Module $msftGraphModule -ErrorAction SilentlyContinue
} Catch {
}
Try {
Remove-Module $azAccountsModule -ErrorAction SilentlyContinue
} Catch {
}
BREAK
}
}
Write-Host "### Connecting To Azure AD Tenant '$aadTenantFQDN' ($aadTenantID) (Connect-MgGraph)..." -ForegroundColor Cyan
Write-Host ""
Try {
If ([String]::IsNullOrEmpty($accessToken)) {
Connect-MgGraph -TenantId $aadTenantID -Scopes "Application.ReadWrite.All" -ErrorAction Stop | Out-Null
} Else {
If ((Get-Help Connect-MgGraph -Parameter accesstoken).type.name -eq "securestring") {
$accessToken = ConvertTo-SecureString $accessToken -AsPlainText -Force
}
Connect-MgGraph -AccessToken $accessToken -ErrorAction Stop | Out-Null
}
} Catch {
Write-Host "Connecting And Authenticating To The Azure AD Tenant '$aadTenantFQDN' Failed (Connect-MgGraph)..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
Write-Host ""
Try {
Remove-Module $msftGraphModule -ErrorAction SilentlyContinue
} Catch {
}
Try {
Remove-Module $azAccountsModule -ErrorAction SilentlyContinue
} Catch {
}
BREAK
}
Write-Host " => Connected To Tenant ID '$aadTenantID' ($aadTenantFQDN)..." -ForegroundColor Green
Write-Host ""
Write-Host ""
###
# Creating/Updating The Purple Knight Vulnerability Scanning App In AAD
###
If ($createOrUpdateApp) {
Write-Host "### Creating/Updating The Purple Knight Vulnerability Scanning App In AAD..." -ForegroundColor Cyan
Write-Host ""
$aadPKVulnerabilityScanApp = Get-MgApplication -Filter "DisplayName eq '$appRegDisplayName'"
If ($aadPKVulnerabilityScanApp) {
$aadPKVulnerabilityScanAppObjectID = $aadPKVulnerabilityScanApp.Id
$aadPKVulnerabilityScanAppApplicationID = $aadPKVulnerabilityScanApp.AppId
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Already Exists..." -ForegroundColor Yellow
Write-Host ""
} Else {
$aadPKVulnerabilityScanAppReplyURL = "http://localhost"
Try {
$aadPKVulnerabilityScanApp = New-MgApplication -DisplayName $appRegDisplayName -SignInAudience AzureADMyOrg -Web @{RedirectUris = @($aadPKVulnerabilityScanAppReplyURL)} -ErrorAction Stop
$aadPKVulnerabilityScanAppObjectID = $aadPKVulnerabilityScanApp.Id
$aadPKVulnerabilityScanAppApplicationID = $aadPKVulnerabilityScanApp.AppId
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Has Been Created Successfully..." -ForegroundColor Green
Write-Host ""
} Catch {
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Failed To Be Created..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
Write-Host ""
Try {
Remove-Module $msftGraphModule -ErrorAction SilentlyContinue
} Catch {
}
Try {
Remove-Module $azAccountsModule -ErrorAction SilentlyContinue
} Catch {
}
BREAK
}
# Creating The Purple Knight Vulnerability Scanning Svc Principal In AAD
Write-Host " => Waiting A Few Seconds Before Continuing..." -ForegroundColor Yellow
Write-Host ""
Start-Sleep -s 10
Try {
$aadPKVulnerabilityScanSvcPrinc = New-MgServicePrincipal -DisplayName $appRegDisplayName -AppId $aadPKVulnerabilityScanAppApplicationID -AccountEnabled:$true -AppRoleAssignmentRequired:$false -ErrorAction Stop
$aadPKVulnerabilityScanSvcPrincObjectID = $aadPKVulnerabilityScanSvcPrinc.Id
$aadPKVulnerabilityScanSvcPrincApplicationID = $aadPKVulnerabilityScanSvcPrinc.AppId
Write-Host " => Purple Knight Vulnerability Scanning Svc Principal In AAD '$appRegDisplayName' Has Been Created Successfully..." -ForegroundColor Green
Write-Host ""
} Catch {
Write-Host " => Purple Knight Vulnerability Scanning Svc Principal In AAD '$appRegDisplayName' Failed To Be Created..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host " => Aborting Script..." -ForegroundColor Red
Write-Host ""
Write-Host ""
Try {
Remove-Module $msftGraphModule -ErrorAction SilentlyContinue
} Catch {
}
Try {
Remove-Module $azAccountsModule -ErrorAction SilentlyContinue
} Catch {
}
BREAK
}
}
# Configuring API Permissions And Granting Admin Consent For The Purple Knight Vulnerability Scanning Svc Principal In AAD
If ($updateAPIPerms) {
$msftGraphSvcPrincipal = Get-MgServicePrincipal -Filter "DisplayName eq 'Microsoft Graph'" # MSFT Graph
$resourceAppId = $msftGraphSvcPrincipal.AppId
$resourceAccess = @()
$msftGraphListOfRequiredPermissions | ForEach-Object{
$appRoleName = $_
$appRoleID = ($msftGraphSvcPrincipal.AppRoles | ?{$_.Value -eq $appRoleName}).Id
$resourceAccess += @{id = $appRoleID; type = "Role"}
}
$requiredResourceAccessListAADPKVulnerabilityScanApp = New-Object -TypeName Microsoft.Graph.PowerShell.Models.MicrosoftGraphRequiredResourceAccess
$requiredResourceAccessListAADPKVulnerabilityScanApp.ResourceAppId = $resourceAppId
$requiredResourceAccessListAADPKVulnerabilityScanApp.ResourceAccess = $resourceAccess
$requiredResourceAccessPSObjectListAADPKVulnerabilityScanApp = @(
[PSCustomObject]@{
resourceAppId = $resourceAppId
resourceAccess = $resourceAccess
}
)
Try {
Update-MgApplication -ApplicationId $aadPKVulnerabilityScanAppObjectID -RequiredResourceAccess $requiredResourceAccessListAADPKVulnerabilityScanApp -ErrorAction Stop
Write-Host " => API Permissions For Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Have Been Configured Successfully..." -ForegroundColor Green
Write-Host ""
} Catch {
Write-Host " => API Permissions For Purple Knight Vulnerability Scanning Svc Principal In AAD '$appRegDisplayName' Failed To Be Configured..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host ""
}
# Inspired By: https://stackoverflow.com/questions/63529599/how-to-grant-admin-consent-to-an-azure-aad-app-in-powershell
$permissionsScopes = @()
$requiredResourceAccessPSObjectListAADPKVulnerabilityScanApp | ForEach-Object {
$resourceAppID = $null
$resourceAppID = $_.resourceAppId
$resourceAccess = $null
$resourceAccess = $_.resourceAccess
$resource = $null
$resource = $(Get-MgServicePrincipal -Filter "AppId eq '$resourceAppID'")
$resourceName = $null
$resourceName = $resource.DisplayName
$resourceAccessValues = @()
$resourceAccess | ForEach-Object{
$resourceAccessType = $null
$resourceAccessType = $_.type
$resourceAccessID = $null
$resourceAccessID = $_.id
$resourceAccessValue = $null
If ($resourceAccessType -eq "Role") {
$resourceAccessValue = "AppRole: " + ($resource.AppRoles | Where-Object{$_.id -eq $resourceAccessID}).Value
}
If ($resourceAccessType -eq "scope") {
$resourceAccessValue = "Scope: " + ($resource.Oauth2Permissions | Where-Object{$_.id -eq $resourceAccessID}).Value
}
$resourceAccessValues += $resourceAccessValue
}
$permissionsScopes += $($resourceName + "|" + $($resourceAccessValues -join ","))
}
$azureContext = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$resourceIDAADPortalMgmtUI = "74658136-14ec-4630-ad9b-26e160ff0fc6" # Resource ID For Azure AD Portal Management UI
$AzureMgmtAccessToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($azureContext.Account, $azureContext.Environment, $azureContext.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, $resourceIDAADPortalMgmtUI).AccessToken
$requestHeaders = @{
'Authorization' = 'Bearer ' + $AzureMgmtAccessToken
'X-Requested-With'= 'XMLHttpRequest'
'x-ms-client-request-id'= [guid]::NewGuid()
'x-ms-correlation-id' = [guid]::NewGuid()
}
$azureMgmtAdminConsentAADPKVulnerabilityScanAppEndpointURL = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$aadPKVulnerabilityScanAppApplicationID/Consent?onBehalfOfAll=true"
Write-Host " => Waiting A Few Seconds Before Continuing To Make Sure The Application, The Service Principal And Permissions Are In Place..." -ForegroundColor Yellow
Write-Host ""
Start-Sleep -s 30
Try {
Invoke-RestMethod -Uri $azureMgmtAdminConsentAADPKVulnerabilityScanAppEndpointURL -Headers $requestHeaders -Method POST -ErrorAction Stop | Out-Null
Write-Host " => Admin Consent Successfully Granted For The Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName'..." -ForegroundColor Green
Write-Host " WARNING: Although Possible, This IS NOT Officially Supported!..." -ForegroundColor Green
Write-Host ""
} Catch {
Write-Host " => Failed To Grant Admin Consent For The Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName'..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host ""
}
}
# Deleting All Existing Client Secrets For The Configured Permissions For The Purple Knight Vulnerability Scanning App In AAD
If ($deleteAllClientSecrets) {
Try {
(Get-MgApplication -ApplicationId $aadPKVulnerabilityScanAppObjectID -ErrorAction Stop).PasswordCredentials | %{Remove-MgApplicationPassword -ApplicationId $aadPKVulnerabilityScanAppObjectID -KeyId $_.KeyId -ErrorAction Stop}
Write-Host " => All Existing Client Secrets For Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Have Been Deleted..." -ForegroundColor Green
Write-Host ""
} Catch {
Write-Host " => All Existing Client Secrets For Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Failed To Be Deleted..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host ""
}
}
# Creating A Client Secret For The Configured Permissions For The Purple Knight Vulnerability Scanning App In AAD
If ($createClientSecret) {
Try {
$startDate = Get-Date
If ($customLifetimeSecretInDays) {
$endDate = $startDate.AddDays($customLifetimeSecretInDays)
} Else {
$endDate = $startDate.AddHours(1)
}
$passwordCred = @{
displayName = "Purple Knight Client Secret (Generated $(Get-Date $startDate -Format 'yyyy-MM-dd HH:mm:ss'))"
startDateTime = $startDate
endDateTime = $endDate
}
$aadPKVulnerabilityScanClientSecret = Add-MgApplicationPassword -ApplicationId $aadPKVulnerabilityScanAppObjectID -PasswordCredential $passwordCred
Write-Host " => Client Secret For Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Has Been Created..." -ForegroundColor Green
Write-Host ""
} Catch {
Write-Host " => Client Secret For Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Failed To Be Created And Configured..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host ""
}
}
# Displaying The Required Data For The Purple Knight Vulnerability Scanning App In AAD
Write-Host "### Displaying The Required Data For The Purple Knight Vulnerability Scanning App In AAD..." -ForegroundColor Cyan
Write-Host ""
Write-Host " => Tenant ID......................: '$aadTenantID'" -ForegroundColor Yellow
Write-Host " => Application Name...............: '$appRegDisplayName'" -ForegroundColor Yellow
Write-Host " => Application Object ID..........: '$aadPKVulnerabilityScanAppObjectID'" -ForegroundColor Yellow
Write-Host " => Application App ID.............: '$aadPKVulnerabilityScanAppApplicationID'" -ForegroundColor Yellow
If ($updateAPIPerms) {
Write-Host " => API Permissions................:" -ForegroundColor Yellow
$permissionsScopes | ForEach-Object{
$resourceApp = $null
$resourceApp = $_.Split("|")[0]
Write-Host " - Resource.....................: $resourceApp..." -ForegroundColor Yellow
$_.Split("|")[1].Split(",") | ForEach-Object{
Write-Host " * Permissions................: $($_)..." -ForegroundColor Yellow
}
}
}
If ($createClientSecret) {
Write-Host " => Client Secret..................: '$($aadPKVulnerabilityScanClientSecret.SecretText)'" -ForegroundColor Yellow
If ($customLifetimeSecretInDays) {
Write-Host " => Custom Lifetime Client Secret..: '$customLifetimeSecretInDays Days'" -ForegroundColor Yellow
} Else {
Write-Host " => Default Lifetime Client Secret.: '1 Hour'" -ForegroundColor Yellow
}
Write-Host " => Start Date.....................: '$($aadPKVulnerabilityScanClientSecret.StartDateTime)'" -ForegroundColor Yellow
Write-Host " => End Date.......................: '$($aadPKVulnerabilityScanClientSecret.EndDateTime)'" -ForegroundColor Yellow
Write-Host ""
Write-Host "WARNING: Make Sure To Store The Client Secret Specified Above In A Secure Location Like E.g. A Password Vault And Restrict Access To That Credential!!!" -ForegroundColor Red
}
Write-Host ""
}
# Listing All Existing Client Secrets For The Purple Knight Vulnerability Scanning App In AAD
If ($listAllClientSecrets) {
$aadPKVulnerabilityScanApp = Get-MgApplication -Filter "DisplayName eq '$appRegDisplayName'"
If ($aadPKVulnerabilityScanApp) {
$aadPKVulnerabilityScanAppObjectID = $aadPKVulnerabilityScanApp.Id
$aadPKVulnerabilityScanAppApplicationID = $aadPKVulnerabilityScanApp.AppId
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Exists In AAD..." -ForegroundColor Yellow
Write-Host ""
# Displaying The Required Data For The Purple Knight Vulnerability Scanning App In AAD
Write-Host "### Displaying The Required Data For The Purple Knight Vulnerability Scanning App In AAD..." -ForegroundColor Cyan
Write-Host ""
Write-Host " => Tenant ID......................: '$aadTenantID'" -ForegroundColor Yellow
Write-Host " => Application Name...............: '$appRegDisplayName'" -ForegroundColor Yellow
Write-Host " => Application Object ID..........: '$aadPKVulnerabilityScanAppObjectID'" -ForegroundColor Yellow
Write-Host " => Application App ID.............: '$aadPKVulnerabilityScanAppApplicationID'" -ForegroundColor Yellow
Write-Host ""
$aadPKVulnerabilityScanClientSecrets = $aadPKVulnerabilityScanApp.PasswordCredentials
If ($aadPKVulnerabilityScanClientSecrets) {
Write-Host " => The Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Has The Following Client Secrets Configured In AAD..." -ForegroundColor Yellow
$aadPKVulnerabilityScanClientSecrets | FT DisplayName,StartDateTime,EndDateTime
} Else {
Write-Host " => The Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' DOES NOT Have Any Client Secrets Configured In AAD..." -ForegroundColor Yellow
Write-Host ""
}
} Else {
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' DOES NOT Exist In AAD..." -ForegroundColor Yellow
Write-Host ""
}
}
###
# Deleting The Purple Knight Vulnerability Scanning App In AAD
###
If ($deleteApp) {
Write-Host "### Deleting The Purple Knight Vulnerability Scanning App In AAD..." -ForegroundColor Cyan
Write-Host ""
$aadPKVulnerabilityScanApp = Get-MgApplication -Filter "DisplayName eq '$appRegDisplayName'"
If ($aadPKVulnerabilityScanApp) {
$deleteConfirmation = Read-Host " => Do You Really Want To Continue And Delete The Specified Purple Knight Vulnerability Scanning App In AAD? [YES | NO]"
Write-Host ""
If ($deleteConfirmation.ToUpper() -eq "YES" -Or $deleteConfirmation.ToUpper() -eq "Y") {
Try {
Remove-MgApplication -ApplicationId $aadPKVulnerabilityScanApp.Id
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Has Been Deleted Successfully..." -ForegroundColor Green
Write-Host ""
Write-Host ""
} Catch {
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' Failed To Be Deleted..." -ForegroundColor Red
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host ""
}
} Else {
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' HAS NOT BEEN Deleted..." -ForegroundColor Yellow
Write-Host ""
Write-Host ""
}
} Else {
Write-Host " => Purple Knight Vulnerability Scanning App In AAD '$appRegDisplayName' DOES NOT Exist..." -ForegroundColor Red
Write-Host ""
Write-Host ""
}
}
###
# Disconnect From Azure (AD)
###
Try {
Disconnect-AzAccount -ErrorAction SilentlyContinue | Out-Null
} Catch {
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host ""
}
Try {
Remove-Module $azAccountsModule -ErrorAction SilentlyContinue
} Catch {
}
Try {
Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
} Catch {
Write-Host ""
Write-Host " - Exception Type......: $($_.Exception.GetType().FullName)" -ForegroundColor Red
Write-Host " - Exception Message...: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " - Error On Script Line: $($_.InvocationInfo.ScriptLineNumber)" -ForegroundColor Red
Write-Host ""
Write-Host ""
}
Try {
Remove-Module $msftGraphModule -ErrorAction SilentlyContinue
} Catch {
}
###
# THE END OF THE SCRIPT
###
Write-Host ""
Write-Host " +++ DONE +++ " -ForegroundColor Cyan
Write-Host ""