forked from microsoft/ARI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AzureResourceInventory.ps1
1549 lines (1226 loc) · 73.7 KB
/
AzureResourceInventory.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
##########################################################################################
# #
# * Azure Resource Inventory ( ARI ) Report Generator * #
# #
# Version: 2.1.10 #
# #
# Date: 12/03/2021 #
# #
##########################################################################################
<#
.SYNOPSIS
This script creates Excel file to Analyze Azure Resources inside a Tenant
.DESCRIPTION
Do you want to analyze your Azure Advisories in a table format? Document it in xlsx format.
.PARAMETER TenantID
Specify the tenant ID you want to create a Resource Inventory.
>>> IMPORTANT: YOU NEED TO USE THIS PARAMETER FOR TENANTS WITH MULTI-FACTOR AUTHENTICATION. <<<
.PARAMETER SubscriptionID
Use this parameter to collect a specific Subscription in a Tenant
.PARAMETER SecurityCenter
Use this parameter to collect Security Center Advisories
.PARAMETER SkipAdvisory
Use this parameter to skip the capture of Azure Advisories
.PARAMETER IncludeTags
Use this parameter to include Tags of every Azure Resources
.PARAMETER Debug
Execute ASCI in debug mode.
.EXAMPLE
Default utilization. Read all tenants you have privileges, select a tenant in menu and collect from all subscriptions:
PS C:\> .\AzureResourceInventory.ps1
Define the Tenant ID:
PS C:\> .\AzureResourceInventory.ps1 -TenantID <your-Tenant-Id>
Define the Tenant ID and for a specific Subscription:
PS C:\>.\AzureResourceInventory.ps1 -TenantID <your-Tenant-Id> -SubscriptionID <your-Subscription-Id>
.NOTES
AUTHORS: Claudio Merola and Renato Gregio - Customer Engineer - Customer Success Unit | Azure Infrastucture/Automation/Devops/Governance | Microsoft
.LINK
https://github.com/azureinventory
Please note that while being developed by a Microsoft employee, Azure inventory Scripts is not a Microsoft service or product. Azure Inventory Scripts are a personal driven project, there are none implicit or explicit obligations related to this project, it is provided 'as is' with no warranties and confer no rights.
#>
param ($TenantID, [switch]$SecurityCenter, $SubscriptionID, $Appid, $Secret, $ResourceGroup, [switch]$SkipAdvisory, [switch]$IncludeTags, [switch]$QuotaUsage, [switch]$Online, [switch]$Diagram , [switch]$Debug, [switch]$Help, [switch]$DeviceLogin)
if ($Debug.IsPresent) {$DebugPreference = 'Continue'}
if ($Debug.IsPresent) {$ErrorActionPreference = "Continue" }Else {$ErrorActionPreference = "silentlycontinue" }
Write-Debug ('Debbuging Mode: On. ErrorActionPreference was set to "Continue", every error will be presented.')
if ($IncludeTags.IsPresent) { $Global:InTag = $true } else { $Global:InTag = $false }
$Global:SRuntime = Measure-Command -Expression {
<######################################################### Help ######################################################################>
Function usageMode() {
Write-Host ""
Write-Host "Parameters"
Write-Host ""
Write-Host " -TenantID <ID> : Specifies the Tenant to be inventoried. "
Write-Host " -SubscriptionID <ID> : Specifies one unique Subscription to be inventoried. "
Write-Host " -ResourceGroup <NAME> : Specifies one unique Resource Group to be inventoried, This parameter requires the -SubscriptionID to work. "
Write-Host " -SkipAdvisory : Do not collect Azure Advisory. "
Write-Host " -SecurityCenter : Include Security Center Data. "
Write-Host " -IncludeTags : Include Resource Tags. "
Write-Host " -Diagram : Create a Visio Diagram. "
Write-Host " -Online : Use Online Modules. "
Write-Host " -Debug : Run in a Debug mode. "
Write-Host ""
Write-Host ""
Write-Host ""
Write-Host "Usage Mode and Examples: "
Write-Host "For CloudShell:"
Write-Host "e.g. />./AzureResourceInventory.ps1"
Write-Host ""
Write-Host "For PowerShell Desktop:"
Write-Host ""
Write-Host "If you do not specify Resource Inventory will be performed on all subscriptions for the selected tenant. "
Write-Host "e.g. />./AzureResourceInventory.ps1"
Write-Host ""
Write-Host "To perform the inventory in a specific Tenant and subscription use <-TenantID> and <-SubscriptionID> parameter "
Write-Host "e.g. />./AzureResourceInventory.ps1 -TenantID <Azure Tenant ID> -SubscriptionID <Subscription ID>"
Write-Host ""
Write-Host "Including Tags:"
Write-Host " By Default Azure Resource inventory do not include Resource Tags."
Write-Host " To include Tags at the inventory use <-IncludeTags> parameter. "
Write-Host "e.g. />./AzureResourceInventory.ps1 -TenantID <Azure Tenant ID> --IncludeTags"
Write-Host ""
Write-Host "Collecting Security Center Data :"
Write-Host " By Default Azure Resource inventory do not collect Security Center Data."
Write-Host " To include Security Center details in the report, use <-SecurityCenter> parameter. "
Write-Host "e.g. />./AzureResourceInventory.ps1 -TenantID <Azure Tenant ID> -SubscriptionID <Subscription ID> -SecurityCenter"
Write-Host ""
Write-Host "Skipping Azure Advisor:"
Write-Host " By Default Azure Resource inventory collects Azure Advisor Data."
Write-Host " To ignore this use <-SkipAdvisory> parameter. "
Write-Host "e.g. />./AzureResourceInventory.ps1 -TenantID <Azure Tenant ID> -SubscriptionID <Subscription ID> -SkipAdvisory"
Write-Host ""
Write-Host "Creating Visio Diagram :"
Write-Host "If you Want to create a Visio Diagram you need to use <-Diagram> parameter."
Write-Host "It's a pre-requisite to run in a Windows with Microsoft Visio Installed"
Write-Host " To include Security Center details in the report, use <-SecurityCenter> parameter. "
Write-Host "e.g. />./AzureResourceInventory.ps1 -TenantID <Azure Tenant ID> -Diagram"
Write-Host ""
Write-Host "Using the latest modules :"
Write-Host " You can use the latest modules. For this use <-Online> parameter."
Write-Host "It's a pre-requisite to have internet access for ARI GitHub repo"
Write-Host "e.g. />./AzureResourceInventory.ps1 -TenantID <Azure Tenant ID> -Online"
Write-Host ""
Write-Host "Running in Debug Mode :"
Write-Host "To run in a Debug Mode use <-Debug> parameter."
Write-Host ".e.g. />/AzureResourceInventory.ps1 -TenantID <Azure Tenant ID> -Debug"
Write-Host ""
}
Function Variables {
Write-Debug ('Cleaning default variables')
$Global:Resources = @()
$Global:Advisories = @()
$Global:Security = @()
$Global:Subscriptions = ''
if ($Online.IsPresent) { $Global:RunOnline = $true }else { $Global:RunOnline = $false }
$Global:Repo = 'https://github.com/azureinventory/ARI/tree/main/Modules'
$Global:RawRepo = 'https://raw.githubusercontent.com/azureinventory/ARI/main'
}
<######################################################### Environment ######################################################################>
Function Extractor {
Write-Debug ('Starting Extractor function')
function checkAzCli() {
Write-Debug ('Starting checkAzCli function')
Write-Host "Validating Az Cli.."
$azcli = az --version
Write-Debug ('Current az cli version: ' + $azcli[0])
if ($null -eq $azcli) {
Read-Host "Azure CLI Not Found. Press <Enter> to finish script"
Exit
}
Write-Host "Validating Az Cli Extension.."
$azcliExt = az extension list --output json | ConvertFrom-Json
$azcliExt = $azcliExt | Where-Object {$_.name -eq 'resource-graph'}
Write-Debug ('Current Resource-Graph Extension Version: ' + $azcliExt.version)
$AzcliExtV = $azcliExt | Where-Object {$_.name -eq 'resource-graph'}
if (!$AzcliExtV) {
Write-Host "Adding Az Cli Extension"
az extension add --name resource-graph
}
Write-Host "Validating ImportExcel Module.."
$VarExcel = Get-InstalledModule -Name ImportExcel -ErrorAction silentlycontinue
Write-Debug ('ImportExcel Module Version: ' + ([string]$VarExcel.Version.Major + '.' + [string]$VarExcel.Version.Minor + '.' + [string]$VarExcel.Version.Build))
if ($null -eq $VarExcel) {
Write-Host "Trying to install ImportExcel Module.."
Install-Module -Name ImportExcel -Force
}
$VarExcel = Get-InstalledModule -Name ImportExcel -ErrorAction silentlycontinue
if ($null -eq $VarExcel) {
Read-Host 'Admininstrator rights required to install ImportExcel Module. Press <Enter> to finish script'
Exit
}
}
function LoginSession() {
Write-Debug ('Starting LoginSession function')
if (!$TenantID) {
write-host "Tenant ID not specified. Use -TenantID parameter if you want to specify directly. "
write-host "Authenticating Azure"
write-host ""
Write-Debug ('Cleaning az account cache')
az account clear | Out-Null
Write-Debug ('Calling az login')
if($DeviceLogin.IsPresent)
{
az login --use-device-code
}
else
{
az login --only-show-errors | Out-Null
}
write-host ""
write-host ""
$Tenants = az account list --query [].homeTenantId -o tsv --only-show-errors | Sort-Object -Unique
Write-Debug ('Checking number of Tenants')
if ($Tenants.Count -eq 1) {
write-host "You have privileges only in One Tenant "
write-host ""
$TenantID = $Tenants
}
else {
write-host "Select the the Azure Tenant ID that you want to connect : "
write-host ""
$SequenceID = 1
foreach ($TenantID in $Tenants) {
write-host "$SequenceID) $TenantID"
$SequenceID ++
}
write-host ""
[int]$SelectTenant = read-host "Select Tenant ( default 1 )"
$defaultTenant = --$SelectTenant
$TenantID = $Tenants[$defaultTenant]
if($DeviceLogin.IsPresent)
{
az login --use-device-code -t $TenantID
}
else
{
az login -t $TenantID --only-show-errors | Out-Null
}
}
write-host "Extracting from Tenant $TenantID"
Write-Debug ('Extracting Subscription details')
$Global:Subscriptions = az account list --output json --only-show-errors | ConvertFrom-Json
$Global:Subscriptions = $Subscriptions | Where-Object { $_.tenantID -eq $TenantID }
if ($SubscriptionID)
{
if($SubscriptionID.count -gt 1)
{
$Global:Subscriptions = $Subscriptions | Where-Object { $_.ID -in $SubscriptionID }
}
else
{
$Global:Subscriptions = $Subscriptions | Where-Object { $_.ID -eq $SubscriptionID }
}
}
}
else {
az account clear | Out-Null
if (!$Appid) {
if($DeviceLogin.IsPresent)
{
az login --use-device-code -t $TenantID
}
else
{
az login -t $TenantID --only-show-errors | Out-Null
}
}
elseif ($Appid -and $Secret -and $tenantid) {
write-host "Using Service Principal Authentication Method"
az login --service-principal -u $appid -p $secret -t $TenantID | Out-Null
}
else{
write-host "You are trying to use Service Principal Authentication Method in a wrong way."
write-host "It's Mandatory to specify Application ID, Secret and Tenant ID in Azure Resource Inventory"
write-host ""
write-host ".\AzureResourceInventory.ps1 -appid <SP AppID> -secret <SP Secret> -tenant <TenantID>"
Exit
}
$Global:Subscriptions = az account list --output json --only-show-errors | ConvertFrom-Json
$Global:Subscriptions = $Subscriptions | Where-Object { $_.tenantID -eq $TenantID }
if ($SubscriptionID)
{
if($SubscriptionID.count -gt 1)
{
$Global:Subscriptions = $Subscriptions | Where-Object { $_.ID -in $SubscriptionID }
}
else
{
$Global:Subscriptions = $Subscriptions | Where-Object { $_.ID -eq $SubscriptionID }
}
}
}
}
function checkPS() {
Write-Debug ('Starting checkPS function')
$CShell = try{Get-CloudDrive}catch{}
if ($CShell) {
write-host 'Azure CloudShell Identified.'
$Global:PlatOS = 'Azure CloudShell'
write-host ""
$Global:DefaultPath = "$HOME/AzureResourceInventory/"
$Global:Subscriptions = az account list --output json --only-show-errors | ConvertFrom-Json
}
else
{
if ($PSVersionTable.Platform -eq 'Unix') {
write-host "PowerShell Unix Identified."
$Global:PlatOS = 'PowerShell Unix'
write-host ""
$Global:DefaultPath = "$HOME/AzureResourceInventory/"
LoginSession
}
else {
write-host "PowerShell Desktop Identified."
$Global:PlatOS = 'PowerShell Desktop'
write-host ""
$Global:DefaultPath = "C:\AzureResourceInventory\"
LoginSession
}
}
}
<###################################################### Checking PowerShell ######################################################################>
checkAzCli
checkPS
#Field for tags
if ($IncludeTags.IsPresent) {
Write-Debug "Tags will be included"
$GraphQueryTags = ",tags "
} else {
Write-Debug "Tags will be excluded"
$GraphQueryTags = ""
}
<###################################################### Subscriptions ######################################################################>
Write-Progress -activity 'Azure Inventory' -Status "1% Complete." -PercentComplete 2 -CurrentOperation 'Discovering Subscriptions..'
$SubCount = $Subscriptions.count
Write-Debug ('Number of Subscriptions Found: ' + $SubCount)
Write-Progress -activity 'Azure Inventory' -Status "3% Complete." -PercentComplete 3 -CurrentOperation "$SubCount Subscriptions found.."
Write-Debug ('Checking report folder: ' + $DefaultPath )
if ((Test-Path -Path $DefaultPath -PathType Container) -eq $false) {
New-Item -Type Directory -Force -Path $DefaultPath | Out-Null
}
<######################################################## INVENTORY LOOPs #######################################################################>
Write-Progress -activity 'Azure Inventory' -Status "4% Complete." -PercentComplete 4 -CurrentOperation "Starting Resources extraction jobs.."
<######################################################### ADVISOR ######################################################################>
$Global:ExtractionRuntime = Measure-Command -Expression {
$Global:Subscri = $Global:Subscriptions.id
if (!($SkipAdvisory.IsPresent)) {
Write-Debug ('Subscriptions To be Gather in Advisories: '+$Subscri.Count)
if ([string]::IsNullOrEmpty($ResourceGroup)) {
Write-Debug ('Resource Group name is not present, extracting advisories for all Resource Groups')
$GraphQuery = "advisorresources | summarize count()"
} else {
$GraphQuery = "advisorresources | where resourceGroup == '$ResourceGroup' | summarize count()"
}
$AdvSize = az graph query -q $GraphQuery --subscriptions $Subscri --output json --only-show-errors | ConvertFrom-Json
$AdvSizeNum = $AdvSize.data.'count_'
Write-Debug ('Advisories: '+$AdvSizeNum)
Write-Progress -activity 'Azure Inventory' -Status "5% Complete." -PercentComplete 5 -CurrentOperation "Starting Advisories extraction jobs.."
if ($AdvSizeNum -ge 1) {
$Loop = $AdvSizeNum / 1000
$Loop = [math]::ceiling($Loop)
$Looper = 0
$Limit = 0
while ($Looper -lt $Loop) {
$Looper ++
Write-Progress -Id 1 -activity "Running Advisory Inventory Job" -Status "$Looper / $Loop of Inventory Jobs" -PercentComplete (($Looper / $Loop) * 100)
if ([string]::IsNullOrEmpty($ResourceGroup)) {
$GraphQuery = "advisorresources | order by id asc"
} else {
$GraphQuery = "advisorresources | where resourceGroup == '$ResourceGroup' | order by id asc"
}
$Advisor = (az graph query -q $GraphQuery --subscriptions $Subscri --skip $Limit --first 1000 --output json --only-show-errors).tolower() | ConvertFrom-Json
$Global:Advisories += $Advisor.data
Start-Sleep 2
$Limit = $Limit + 1000
}
Write-Progress -Id 1 -activity "Running Advisory Inventory Job" -Status "Completed" -Completed
}
}
<######################################################### Security Center ######################################################################>
if ($SecurityCenter.IsPresent) {
Write-Progress -activity 'Azure Inventory' -Status "6% Complete." -PercentComplete 6 -CurrentOperation "Starting Security Advisories extraction jobs.."
Write-Host " Azure Resource Inventory are collecting Security Center Advisories."
Write-Host " Collecting Security Center Can increase considerably the execution time of Azure Resource Inventory and the size of final report "
Write-Host " "
Write-Debug ('Extracting total number of Security Advisories from Tenant')
$SecSize = az graph query -q "securityresources | where properties['status']['code'] == 'Unhealthy' | summarize count()" --subscriptions $Subscri --output json --only-show-errors | ConvertFrom-Json
$SecSizeNum = $SecSize.data.'count_'
if ($SecSizeNum -ge 1) {
$Loop = $SecSizeNum / 1000
$Loop = [math]::ceiling($Loop)
$Looper = 0
$Limit = 0
while ($Looper -lt $Loop) {
$Looper ++
Write-Progress -Id 1 -activity "Running Security Advisory Inventory Job" -Status "$Looper / $Loop of Inventory Jobs" -PercentComplete (($Looper / $Loop) * 100)
$GraphQuery = "securityresources | where properties['status']['code'] == 'Unhealthy' | order by id asc"
$SecCenter = (az graph query -q $GraphQuery --subscriptions $Subscri --skip $Limit --first 1000 --output json --only-show-errors).tolower() | ConvertFrom-Json
$Global:Security += $SecCenter.data
Start-Sleep 3
$Limit = $Limit + 1000
}
Write-Progress -Id 1 -activity "Running Security Advisory Inventory Job" -Status "Completed" -Completed
}
}
else {
Write-Host " "
Write-Host " To include Security Center details in the report, use <-SecurityCenter> parameter. "
Write-Host " "
}
Write-Progress -activity 'Azure Inventory' -PercentComplete 20
Write-Progress -Id 1 -activity "Running Inventory Jobs" -Status "100% Complete." -Completed
if(![string]::IsNullOrEmpty($ResourceGroup) -and [string]::IsNullOrEmpty($SubscriptionID))
{
Write-Debug ('Resource Group Name present, but missing Subscription ID.')
Write-Host ''
Write-Host 'If Using the -ResourceGroup Parameter, the Subscription ID must be informed'
Write-Host ''
Exit
}
if(![string]::IsNullOrEmpty($ResourceGroup) -and ![string]::IsNullOrEmpty($SubscriptionID))
{
Write-Debug ('Extracting Resources from Subscription: '+$SubscriptionID+'. And from Resource Group: '+$ResourceGroup)
$GraphQuery = "resources | where resourceGroup == '$ResourceGroup' and strlen(properties.definition.actions) < 123000 | summarize count()"
$EnvSize = az graph query -q $GraphQuery --subscriptions $Subscri --output json --only-show-errors | ConvertFrom-Json
$EnvSizeNum = $EnvSize.data.'count_'
if ($EnvSizeNum -ge 1) {
$Loop = $EnvSizeNum / 1000
$Loop = [math]::ceiling($Loop)
$Looper = 0
$Limit = 0
while ($Looper -lt $Loop) {
$GraphQuery = "resources | where resourceGroup == '$ResourceGroup' and strlen(properties.definition.actions) < 123000 | project id,name,type,tenantId,kind,location,resourceGroup,subscriptionId,managedBy,sku,plan,properties,identity,zones,extendedLocation$($GraphQueryTags) | order by id asc"
$Resource = (az graph query -q $GraphQuery --subscriptions $Subscri --skip $Limit --first 1000 --output json --only-show-errors).tolower() | ConvertFrom-Json
$Global:Resources += $Resource.data
Start-Sleep 2
$Looper ++
Write-Progress -Id 1 -activity "Running Resource Inventory Job" -Status "$Looper / $Loop of Inventory Jobs" -PercentComplete (($Looper / $Loop) * 100)
$Limit = $Limit + 1000
}
}
}
elseif([string]::IsNullOrEmpty($ResourceGroup) -and ![string]::IsNullOrEmpty($SubscriptionID))
{
Write-Debug ('Extracting Resources from Subscription: '+$SubscriptionID+'.')
$GraphQuery = "resources | where strlen(properties.definition.actions) < 123000 | summarize count()"
$EnvSize = az graph query -q $GraphQuery --output json --subscriptions $Subscri --only-show-errors | ConvertFrom-Json
$EnvSizeNum = $EnvSize.data.'count_'
if ($EnvSizeNum -ge 1) {
$Loop = $EnvSizeNum / 1000
$Loop = [math]::ceiling($Loop)
$Looper = 0
$Limit = 0
while ($Looper -lt $Loop) {
$GraphQuery = "resources | where strlen(properties.definition.actions) < 123000 | project id,name,type,tenantId,kind,location,resourceGroup,subscriptionId,managedBy,sku,plan,properties,identity,zones,extendedLocation$($GraphQueryTags) | order by id asc"
$Resource = (az graph query -q $GraphQuery --subscriptions $Subscri --skip $Limit --first 1000 --output json --only-show-errors).tolower() | ConvertFrom-Json
$Global:Resources += $Resource.data
Start-Sleep 2
$Looper ++
Write-Progress -Id 1 -activity "Running Resource Inventory Job" -Status "$Looper / $Loop of Inventory Jobs" -PercentComplete (($Looper / $Loop) * 100)
$Limit = $Limit + 1000
}
}
} else {
$GraphQuery = "resources | where strlen(properties.definition.actions) < 123000 | summarize count()"
$EnvSize = az graph query -q $GraphQuery --subscriptions $Subscri --output json --only-show-errors | ConvertFrom-Json
$EnvSizeNum = $EnvSize.data.'count_'
if ($EnvSizeNum -ge 1) {
$Loop = $EnvSizeNum / 1000
$Loop = [math]::ceiling($Loop)
$Looper = 0
$Limit = 0
while ($Looper -lt $Loop) {
$GraphQuery = "resources | where strlen(properties.definition.actions) < 123000 | project id,name,type,tenantId,kind,location,resourceGroup,subscriptionId,managedBy,sku,plan,properties,identity,zones,extendedLocation$($GraphQueryTags) | order by id asc"
$Resource = (az graph query -q $GraphQuery --subscriptions $Subscri --skip $Limit --first 1000 --output json --only-show-errors).tolower() | ConvertFrom-Json
$Global:Resources += $Resource.data
Start-Sleep 2
$Looper ++
Write-Progress -Id 1 -activity "Running Resource Inventory Job" -Status "$Looper / $Loop of Inventory Jobs" -PercentComplete (($Looper / $Loop) * 100)
$Limit = $Limit + 1000
}
}
Write-Progress -Id 1 -activity "Running Resource Inventory Job" -Status "$Looper / $Loop of Inventory Jobs" -PercentComplete (($Looper / $Loop) * 100)
}
#AVD Details
$AVDSize = az graph query -q "desktopvirtualizationresources | summarize count()" --subscriptions $Subscri --output json --only-show-errors | ConvertFrom-Json
$AVDSizeNum = $AVDSize.data.'count_'
if ($AVDSizeNum -ge 1) {
$Loop = $AVDSizeNum / 1000
$Loop = [math]::ceiling($Loop)
$Looper = 0
$Limit = 0
while ($Looper -lt $Loop) {
$GraphQuery = "desktopvirtualizationresources | project id,name,type,tenantId,kind,location,resourceGroup,subscriptionId,managedBy,sku,plan,properties,identity,zones,extendedLocation$($GraphQueryTags) | order by id asc"
$AVD = (az graph query -q $GraphQuery --subscriptions $Subscri --skip $Limit --first 1000 --output json --only-show-errors).tolower() | ConvertFrom-Json
$Global:Resources += $AVD.data
Start-Sleep 2
$Looper ++
$Limit = $Limit + 1000
}
}
if($QuotaUsage.isPresent)
{
Start-Job -Name 'Quota Usage' -ScriptBlock {
$Location = @()
Foreach($Sub in $($args[1]))
{
$Locs = ($($args[0]) | Where-Object {$_.subscriptionId -eq $Sub.id -and $_.Type -in 'microsoft.compute/virtualmachines','microsoft.compute/virtualmachinescalesets'} | Group-Object -Property Location).name
$Val = @{
'Loc' = $Locs;
'Sub' = $Sub.name
}
$Location += $Val
}
$Quotas = @()
Foreach($Loc in $Location)
{
if($Loc.Loc.count -eq 1)
{
$Quota = az vm list-usage --location $Loc.Loc --subscription $Loc.Sub -o json | ConvertFrom-Json
$Quota = $Quota | Where-Object {$_.CurrentValue -ge 1}
$Q = @{
'Location' = $Loc.Loc;
'Subscription' = $Loc.Sub;
'Data' = $Quota
}
$Quotas += $Q
}
else {
foreach($Loc1 in $Loc.loc)
{
$Quota = az vm list-usage --location $Loc1 --subscription $Loc.Sub -o json | ConvertFrom-Json
$Quota = $Quota | Where-Object {$_.CurrentValue -ge 1}
$Q = @{
'Location' = $Loc1;
'Subscription' = $Loc.Sub;
'Data' = $Quota
}
$Quotas += $Q
}
}
}
$Quotas
} -ArgumentList $Global:Resources, $Global:Subscriptions
}
}
}
<######################################################### END Extractor Function ######################################################################>
<######################################################### Creating Excel File ######################################################################>
Function RunMain {
$Global:ReportingRunTime = Measure-Command -Expression {
#### Creating Excel file variable:
$Global:File = ($DefaultPath + "AzureResourceInventory_Report_" + (get-date -Format "yyyy-MM-dd_HH_mm") + ".xlsx")
$Global:DFile = ($DefaultPath + "AzureResourceInventory_Diagram_" + (get-date -Format "yyyy-MM-dd_HH_mm") + ".vsdx")
$Global:DDFile = ($DefaultPath + "AzureResourceInventory_Diagram_" + (get-date -Format "yyyy-MM-dd_HH_mm") + ".xml")
Write-Debug ('Excel file:' + $File)
#### Generic Conditional Text rules, Excel style specifications for the spreadsheets and tables:
$Global:TableStyle = "Light20"
Write-Debug ('Excel Table Style used: ' + $TableStyle)
Write-Progress -activity 'Azure Inventory' -Status "21% Complete." -PercentComplete 21 -CurrentOperation "Starting to process extraction data.."
<######################################################### IMPORT UNSUPPORTED VERSION LIST ######################################################################>
Write-Debug ('Importing List of Unsupported Versions.')
If ($RunOnline -eq $true) {
Write-Debug ('Looking for the following file: '+$RawRepo + '/Extras/Support.json')
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($RawRepo + '/Extras/Support.json')
}
Else {
if($PSScriptRoot -like '*\*')
{
Write-Debug ('Looking for the following file: '+$PSScriptRoot + '\Extras\Support.json')
$ModuSeq0 = New-Object System.IO.StreamReader($PSScriptRoot + '\Extras\Support.json')
}
else
{
Write-Debug ('Looking for the following file: '+$PSScriptRoot + '/Extras/Support.json')
$ModuSeq0 = New-Object System.IO.StreamReader($PSScriptRoot + '/Extras/Support.json')
}
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$Unsupported = $ModuSeq | ConvertFrom-Json
$DataActive = ('Azure Resource Inventory Reporting (' + ($resources.count) + ') Resources')
<######################################################### DIAGRAM JOB ######################################################################>
Write-Debug ('Checking if Draw.io Diagram Job Should be Run.')
if ($Diagram.IsPresent) {
Write-Debug ('Starting Draw.io Diagram Processing Job.')
Start-job -Name 'DrawDiagram' -ScriptBlock {
If ($($args[5]) -eq $true) {
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[7]) + '/Extras/DrawIODiagram.ps1')
}
Else {
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '\Extras\DrawIODiagram.ps1')
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$ScriptBlock = [Scriptblock]::Create($ModuSeq)
$DrawRun = ([PowerShell]::Create()).AddScript($ScriptBlock).AddArgument($($args[1])).AddArgument($($args[2])).AddArgument($($args[3])).AddArgument($($args[4]))
$DrawJob = $DrawRun.BeginInvoke()
while ($DrawJob.IsCompleted -contains $false) {}
$DrawRun.EndInvoke($DrawJob)
$DrawRun.Dispose()
} -ArgumentList $PSScriptRoot, $Subscriptions, $Resources, $Advisories, $DDFile, $RunOnline, $Repo, $RawRepo | Out-Null
}
<######################################################### DIAGRAM JOB ######################################################################>
Write-Debug ('Checking if Visio Diagram Job Should be Run.')
if ($Diagram.IsPresent) {
Write-Debug ('Starting Visio Diagram Processing Job.')
Start-job -Name 'VisioDiagram' -ScriptBlock {
If ($($args[5]) -eq $true) {
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[7]) + '/Extras/VisioDiagram.ps1')
}
Else {
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '\Extras\VisioDiagram.ps1')
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$ScriptBlock = [Scriptblock]::Create($ModuSeq)
$VisioRun = ([PowerShell]::Create()).AddScript($ScriptBlock).AddArgument($($args[1])).AddArgument($($args[2])).AddArgument($($args[3])).AddArgument($($args[4]))
$VisioJob = $VisioRun.BeginInvoke()
while ($VisioJob.IsCompleted -contains $false) {}
$VisioRun.EndInvoke($VisioJob)
$VisioRun.Dispose()
} -ArgumentList $PSScriptRoot, $Subscriptions, $Resources, $Advisories, $DFile, $RunOnline, $Repo, $RawRepo | Out-Null
}
<######################################################### SECURITY CENTER JOB ######################################################################>
Write-Debug ('Checking If Should Run Security Center Job.')
if ($SecurityCenter.IsPresent) {
Write-Debug ('Starting Security Job.')
Start-Job -Name 'Security' -ScriptBlock {
If ($($args[5]) -eq $true) {
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[6]) + '/Extras/SecurityCenter.ps1')
}
Else {
if($($args[0]) -like '*\*')
{
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '\Extras\SecurityCenter.ps1')
}
else
{
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '/Extras/SecurityCenter.ps1')
}
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$ScriptBlock = [Scriptblock]::Create($ModuSeq)
$SecRun = ([PowerShell]::Create()).AddScript($ScriptBlock).AddArgument($($args[1])).AddArgument($($args[2])).AddArgument($($args[3]))
$SecJob = $SecRun.BeginInvoke()
while ($SecJob.IsCompleted -contains $false) {}
$SecResult = $SecRun.EndInvoke($SecJob)
$SecRun.Dispose()
$SecResult
} -ArgumentList $PSScriptRoot, $Subscriptions , $Security, 'Processing' , $File, $RunOnline, $RawRepo | Out-Null
}
<######################################################### ADVISORY JOB ######################################################################>
Write-Debug ('Checking If Should Run Advisory Job.')
if (!$SkipAdvisory.IsPresent) {
Write-Debug ('Starting Advisory Processing Job.')
Start-Job -Name 'Advisory' -ScriptBlock {
If ($($args[4]) -eq $true) {
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[5]) + '/Extras/Advisory.ps1')
}
Else {
if($($args[0]) -like '*\*')
{
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '\Extras\Advisory.ps1')
}
else
{
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '/Extras/Advisory.ps1')
}
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$ScriptBlock = [Scriptblock]::Create($ModuSeq)
$AdvRun = ([PowerShell]::Create()).AddScript($ScriptBlock).AddArgument($($args[1])).AddArgument($($args[2])).AddArgument($($args[3]))
$AdvJob = $AdvRun.BeginInvoke()
while ($AdvJob.IsCompleted -contains $false) {}
$AdvResult = $AdvRun.EndInvoke($AdvJob)
$AdvRun.Dispose()
$AdvResult
} -ArgumentList $PSScriptRoot, $Advisories, 'Processing' , $File, $RunOnline, $RawRepo | Out-Null
}
<######################################################### SUBSCRIPTIONS JOB ######################################################################>
Write-Debug ('Starting Subscriptions job.')
Start-Job -Name 'Subscriptions' -ScriptBlock {
If ($($args[4]) -eq $true) {
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[5]) + '/Extras/Subscriptions.ps1')
}
Else {
if($($args[0]) -like '*\*')
{
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '\Extras\Subscriptions.ps1')
}
else
{
$ModuSeq0 = New-Object System.IO.StreamReader($($args[0]) + '/Extras/Subscriptions.ps1')
}
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$ScriptBlock = [Scriptblock]::Create($ModuSeq)
$SubRun = ([PowerShell]::Create()).AddScript($ScriptBlock).AddArgument($($args[1])).AddArgument($($args[2])).AddArgument($($args[3])).AddArgument($($args[4]))
$SubJob = $SubRun.BeginInvoke()
while ($SubJob.IsCompleted -contains $false) {}
$SubResult = $SubRun.EndInvoke($SubJob)
$SubRun.Dispose()
$SubResult
} -ArgumentList $PSScriptRoot, $Subscriptions, $Resources, 'Processing' , $File, $RunOnline, $RawRepo | Out-Null
<######################################################### COMPUTE RESOURCE GROUP JOB ######################################################################>
Write-Debug ('Starting Compute Processing Job.')
Start-job -Name 'Compute' -ScriptBlock {
If ($($args[8]) -eq $true) {
$OnlineRepo = Invoke-WebRequest -Uri ($($args[9]) + '/Compute')
$Modules = $OnlineRepo.Links | Where-Object { $_.href -like '*.ps1' }
$Modules = $Modules.href
}
Else {
if($($args[0]) -like '*\*')
{
$Modules = Get-ChildItem -Path ($($args[0]) + '\Modules\Compute\*.ps1') -Recurse
}
else
{
$Modules = Get-ChildItem -Path ($($args[0]) + '/Modules/Compute/*.ps1') -Recurse
}
}
$job = @()
foreach ($Module in $Modules) {
If ($($args[8]) -eq $true) {
$Modul = $Module.split('/')
$ModName = $Modul[7].Substring(0, $Modul[7].length - ".ps1".length)
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[10]) + '/Modules/' + $Modul[6] + '/' + $Modul[7])
} Else {
$ModName = $Module.Name.Substring(0, $Module.Name.length - ".ps1".length)
$ModuSeq0 = New-Object System.IO.StreamReader($Module.FullName)
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$ScriptBlock = [Scriptblock]::Create($ModuSeq)
New-Variable -Name ('ModRun' + $ModName)
New-Variable -Name ('ModJob' + $ModName)
Set-Variable -Name ('ModRun' + $ModName) -Value ([PowerShell]::Create()).AddScript($ScriptBlock).AddArgument($($args[0])).AddArgument($($args[1])).AddArgument($($args[2])).AddArgument($($args[3])).AddArgument($($args[4]))
Set-Variable -Name ('ModJob' + $ModName) -Value ((get-variable -name ('ModRun' + $ModName)).Value).BeginInvoke()
$job += (get-variable -name ('ModJob' + $ModName)).Value
}
while ($Job.Runspace.IsCompleted -contains $false) {}
foreach ($Module in $Modules) {
If ($($args[8]) -eq $true) {
$Modul = $Module.split('/')
$ModName = $Modul[7].Substring(0, $Modul[7].length - ".ps1".length)
} Else {
$ModName = $Module.Name.Substring(0, $Module.Name.length - ".ps1".length)
}
New-Variable -Name ('ModValue' + $ModName)
Set-Variable -Name ('ModValue' + $ModName) -Value (((get-variable -name ('ModRun' + $ModName)).Value).EndInvoke((get-variable -name ('ModJob' + $ModName)).Value))
}
$Hashtable = New-Object System.Collections.Hashtable
foreach ($Module in $Modules) {
If ($($args[8]) -eq $true) {
$Modul = $Module.split('/')
$ModName = $Modul[7].Substring(0, $Modul[7].length - ".ps1".length)
} Else {
$ModName = $Module.Name.Substring(0, $Module.Name.length - ".ps1".length)
}
$Hashtable["$ModName"] = (get-variable -name ('ModValue' + $ModName)).Value
}
$Hashtable
} -ArgumentList $PSScriptRoot, $Subscriptions, $InTag, $Resources, 'Processing' , $null, $null, $null, $RunOnline, $Repo, $RawRepo | Out-Null
<######################################################### NETWORK RESOURCE GROUP JOB ######################################################################>
Write-Debug ('Starting Networking Processing Job.')
Start-job -Name 'Networking' -ScriptBlock {
If ($($args[8]) -eq $true) {
$OnlineRepo = Invoke-WebRequest -Uri ($($args[9]) + '/Networking')
$Modules = $OnlineRepo.Links | Where-Object { $_.href -like '*.ps1' }
$Modules = $Modules.href
}
Else {
if($($args[0]) -like '*\*')
{
$Modules = Get-ChildItem -Path ($($args[0]) + '\Modules\Networking\*.ps1') -Recurse
}
else
{
$Modules = Get-ChildItem -Path ($($args[0]) + '/Modules/Networking/*.ps1') -Recurse
}
}
$job = @()
foreach ($Module in $Modules) {
If ($($args[8]) -eq $true) {
$Modul = $Module.split('/')
$ModName = $Modul[7].Substring(0, $Modul[7].length - ".ps1".length)
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[10]) + '/Modules/' + $Modul[6] + '/' + $Modul[7])
} Else {
$ModName = $Module.Name.Substring(0, $Module.Name.length - ".ps1".length)
$ModuSeq0 = New-Object System.IO.StreamReader($Module.FullName)
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}
$ScriptBlock = [Scriptblock]::Create($ModuSeq)
New-Variable -Name ('ModRun' + $ModName)
New-Variable -Name ('ModJob' + $ModName)
Set-Variable -Name ('ModRun' + $ModName) -Value ([PowerShell]::Create()).AddScript($ScriptBlock).AddArgument($($args[0])).AddArgument($($args[1])).AddArgument($($args[2])).AddArgument($($args[3])).AddArgument($($args[4]))
Set-Variable -Name ('ModJob' + $ModName) -Value ((get-variable -name ('ModRun' + $ModName)).Value).BeginInvoke()
$job += (get-variable -name ('ModJob' + $ModName)).Value
}
while ($Job.Runspace.IsCompleted -contains $false) {}
foreach ($Module in $Modules) {
If ($($args[8]) -eq $true) {
$Modul = $Module.split('/')
$ModName = $Modul[7].Substring(0, $Modul[7].length - ".ps1".length)
} Else {
$ModName = $Module.Name.Substring(0, $Module.Name.length - ".ps1".length)
}
New-Variable -Name ('ModValue' + $ModName)
Set-Variable -Name ('ModValue' + $ModName) -Value (((get-variable -name ('ModRun' + $ModName)).Value).EndInvoke((get-variable -name ('ModJob' + $ModName)).Value))
}
$Hashtable = New-Object System.Collections.Hashtable
foreach ($Module in $Modules) {
If ($($args[8]) -eq $true) {
$Modul = $Module.split('/')
$ModName = $Modul[7].Substring(0, $Modul[7].length - ".ps1".length)
} Else {
$ModName = $Module.Name.Substring(0, $Module.Name.length - ".ps1".length)
}
$Hashtable["$ModName"] = (get-variable -name ('ModValue' + $ModName)).Value
}
$Hashtable
} -ArgumentList $PSScriptRoot, $Subscriptions, $InTag, $Resources, 'Processing' , $null, $null, $null, $RunOnline, $Repo, $RawRepo | Out-Null
<######################################################### INFRASTRUCTURE RESOURCE GROUP JOB ######################################################################>
Write-Debug ('Starting Infrastructure Processing Job.')
Start-job -Name 'Infrastructure' -ScriptBlock {
If ($($args[8]) -eq $true) {
$OnlineRepo = Invoke-WebRequest -Uri ($($args[9]) + '/Infrastructure')
$Modules = $OnlineRepo.Links | Where-Object { $_.href -like '*.ps1' }
$Modules = $Modules.href
}
Else {
if($($args[0]) -like '*\*')
{
$Modules = Get-ChildItem -Path ($($args[0]) + '\Modules\Infrastructure\*.ps1') -Recurse
}
else
{
$Modules = Get-ChildItem -Path ($($args[0]) + '/Modules/Infrastructure/*.ps1') -Recurse
}
}
$job = @()
foreach ($Module in $Modules) {
If ($($args[8]) -eq $true) {
$Modul = $Module.split('/')
$ModName = $Modul[7].Substring(0, $Modul[7].length - ".ps1".length)
$ModuSeq = (New-Object System.Net.WebClient).DownloadString($($args[10]) + '/Modules/' + $Modul[6] + '/' + $Modul[7])
} Else {
$ModName = $Module.Name.Substring(0, $Module.Name.length - ".ps1".length)
$ModuSeq0 = New-Object System.IO.StreamReader($Module.FullName)
$ModuSeq = $ModuSeq0.ReadToEnd()
$ModuSeq0.Dispose()
}