-
Notifications
You must be signed in to change notification settings - Fork 17
/
azure-az-log-reader.ps1
1511 lines (1301 loc) · 48.6 KB
/
azure-az-log-reader.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
<#
.SYNOPSIS
powershell script to query azure rm logs used with quickstart template deployment
.DESCRIPTION
github: https://raw.githubusercontent.com/jagilber/powershellScripts/master/azure-az-log-reader.ps1
gallery: https://gallery.technet.microsoft.com/Azure-Resource-Manager-c1ce252c
script authenticates to azure rm
runs get-azlog and get-azresourcegroupdeployment
colors certain event and deployment operations
listbox allows for viewing specific event and deployment details
can export all events / deployments to text file
requires wmf 5 +
requires az sdk
.NOTES
Author : jagilber
File Name : azure-az-log-reader.ps1
Version : 180729 fix for localized event format changes
History :
170802 add resourcegroup name to all deployment events
.EXAMPLE
.\azure-az-log-reader.ps1
query azure rm for all resource manager and deployment logs
.EXAMPLE
.\azure-az-log-reader.ps1 -detail
query azure rm for all resource manager logs and output additional detail to console
.EXAMPLE
.\azure-az-log-reader.ps1 -deploymentname rds-deployment -resourcegroupname rds-1
query azure rm for all resource manager and deployment logs for rds-deployment and rds-1
.PARAMETER cacheMinutes
optional int parameter to keep cache of resource groups and deployments before requerying. default is 5 minutes.
.PARAMETER deploymentName
optional string parameter to view specific deployment
.PARAMETER detail
optional switch parameter to view event detail in console
.PARAMETER enumSubscriptions
optional switch to enumerate subscriptions for selection to use
.PARAMETER eventStartTime
optional date parameter to view logs from specific time. default is -1 day. azure does not keep some events for more than a couple of hours.
.PARAMETER resourcegroupName
optional string parameter to view specific resource group
.PARAMETER subscriptionId
optional string parameter to specify subscription id to use
.PARAMETER update
optional switch to check github for latest version of script
#>
[CmdletBinding()]
param (
[int]$cacheMinutes = 5,
[string]$deploymentName,
[switch]$detail,
[switch]$enumSubscriptions,
[DateTime]$eventStartTime = [DateTime]::MinValue,
[string]$resourceGroupName,
[string]$subscriptionId,
[switch]$update
)
$ErrorActionPreference = "Continue" #"SilentlyContinue"
$WarningPreference = "SilentlyContinue"
$error.Clear()
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
$global:cacheMinutes = $cacheMinutes
$global:completed = 0
$global:deployments = @{}
$global:deploymentUpdate = $eventStartTime
$global:eventStartTime = $eventStartTime
$global:exportFile = "azure-az-log-reader-export.txt"
$global:groups = @{}
$global:index = @{}
$global:jobName = "bgJob"
$global:listbox = $null
$global:listboxEvent = $null
[timespan]$global:refreshTime = "0:0:30.0"#"0:1:00.0"
$global:resourcegroupUpdate = $eventStartTime
$global:scriptName = $null
$global:subscription = $subscriptionId
$global:timer = $null
$global:window = $null
$updateUrl = "https://raw.githubusercontent.com/jagilber/powershellScripts/master/azure-az-log-reader.ps1"
$global:profileContext = "$($env:TEMP)\ProfileContext.ctx"
# ----------------------------------------------------------------------------------------------------------------
function main()
{
[xml]$xaml = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window" Title="$($MyInvocation.ScriptName)" WindowStartupLocation = "CenterScreen" ResizeMode="CanResize"
ShowInTaskbar = "True" Background = "lightgray" Width="1200" Height="800">
<DockPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="5" />
<RowDefinition Height="500" />
</Grid.RowDefinitions>
<Label x:Name="labelRefresh" Width="100" Margin="0,0,0,0" HorizontalAlignment="Left" Content="Last Refresh:" Grid.Row="0"/>
<Label x:Name="labelRefreshTime" Width="100" Margin="75,0,0,0" HorizontalAlignment="Left" Content="" Grid.Row="0"/>
<Label x:Name="labelGroups" Width="130" Margin="150,0,0,0" HorizontalAlignment="Left" Content="Monitoring Groups:" Grid.Row="0"/>
<Label x:Name="labelGroupsCount" Width="50" Margin="260,0,0,0" HorizontalAlignment="Left" Content="" Grid.Row="0"/>
<Label x:Name="labelDeployments" Width="145" Margin="300,0,0,0" HorizontalAlignment="Left" Content="Monitoring Deployments:" Grid.Row="0"/>
<Label x:Name="labelDeploymentsCount" Width="50" Margin="440,0,0,0" HorizontalAlignment="Left" Content="" Grid.Row="0"/>
<Label x:Name="labelEvents" Width="100" Margin="480,0,0,0" HorizontalAlignment="Left" Content="Events Count:" Grid.Row="0"/>
<Label x:Name="labelEventsCount" Width="50" Margin="560,0,0,0" HorizontalAlignment="Left" Content="" Grid.Row="0"/>
<Button x:Name="exportButton" Width="100" Margin="0,0,200,0" HorizontalAlignment="Right" Content="Export" Grid.Row="0"/>
<Button x:Name="refreshButton" Width="100" Margin="0,0,0,0" HorizontalAlignment="Right" Content="Refresh" Grid.Row="0"/>
<Button x:Name="clearButton" Width="100" Margin="0,0,100,0" HorizontalAlignment="Right" Content="Clear" Grid.Row="0"/>
<ListBox x:Name="listbox" Grid.Row="1" Height="Auto" />
<GridSplitter Grid.Row="2" Height="5" HorizontalAlignment="Stretch" />
<ListBox x:Name="listboxEvent" Grid.Row="3" Height="Auto" />
</Grid>
</DockPanel>
</Window>
"@
set-location $psscriptroot
authenticate-az
# set sub if passed as argument. requires auth
if (![string]::IsNullOrEmpty($subscriptionId) -or $enumSubscriptions)
{
if ($enumSubscriptions)
{
$null = get-subscriptions
}
else
{
# set subscription
Set-azContext -SubscriptionId $subscriptionId
# save context for jobs
Save-azContext -Path $global:profileContext -Force
}
}
$global:Window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))
$global:timer = new-object Windows.Threading.DispatcherTimer
$global:scriptname = [IO.Path]::GetFileNameWithoutExtension($MyInvocation.ScriptName)
if ($update)
{
if ((get-update -updateUrl $updateUrl -destinationFile $global:scriptname))
{
write-host "file updated. restart script."
return
}
}
#Connect to Controls
$clearButton = $global:Window.FindName('clearButton')
$exportButton = $global:Window.FindName('exportButton')
$refreshButton = $global:Window.FindName('refreshButton')
$refreshLabel = $global:Window.FindName('labelRefreshTime')
$groupsLabel = $global:Window.FindName('labelGroupsCount')
$deploymentsLabel = $global:Window.FindName('labelDeploymentsCount')
$eventsLabel = $global:Window.FindName('labelEventsCount')
$global:listbox = $global:Window.FindName('listbox')
$global:listboxEvent = $global:Window.FindName('listboxEvent')
$global:listbox.Add_SelectionChanged( {open-event})
if ($global:eventStartTime -eq [DateTime]::MinValue)
{
$global:eventStartTime = ([DateTime]::Now).AddDays(-1)
}
else
{
$eventStartTimeConvert = [DateTime]::MinValue
if ([DateTime]::TryParse($global:eventStartTime, [ref] $global:eventStartTimeConvert))
{
$global:eventStartTime = $eventStartTimeConvert
}
else
{
$global:eventStartTime = ([DateTime]::Now).AddDays(-1)
}
}
$global:resourcegroupUpdate = $global:eventStartTime
$global:deploymentUpdate = $global:eventStartTime
$eventStartTime = $global:eventStartTime
$global:Window.Add_Closing( {
$global:completed = 1
$global:timer.Stop()
get-job -Name $global:jobName | receive-job
get-job -Name $global:jobName | remove-job -Force
})
$global:Window.Add_Loaded( {
write-host "form loaded:"
reset-list
$global:timer.Add_Tick( {
if ($global:completed)
{
$global:timer.Stop()
}
write-verbose "$([DateTime]::Now) timer start routine"
process-results -jobResults (receive-backgroundJob)
write-verbose "$([DateTime]::Now) finished timer"
})
$deploymentsLabel.Content = $global:deployments.Count
$groupsLabel.Content = $global:groups.Count
$refreshLabel.Content = [DateTime]::Now.ToLongTimeString()
$eventsLabel.Content = $global:listbox.Items.Count
#Start timer
$global:timer.Interval = new-object TimeSpan ($global:refreshTime.Ticks / 2)
$global:timer.Start()
})
#Events
$clearButton.Add_Click( { clear-list })
$exportButton.Add_Click( { export-list })
$refreshButton.Add_Click( { reset-list })
try
{
$null = start-backgroundJob
$global:Window.ShowDialog()
}
catch
{
write-host "window:exception:$($error | out-string)`r`n$($psitem.ScriptStackTrace)"
$error.Clear()
}
finally
{
$global:completed = 1
$global:timer.Stop()
get-job -Name $global:jobName -ErrorAction SilentlyContinue | receive-job -ErrorAction SilentlyContinue
get-job -Name $global:jobName -ErrorAction SilentlyContinue | remove-job -Force -ErrorAction SilentlyContinue
if ([IO.File]::Exists($global:profileContext))
{
[IO.File]::Delete($global:profileContext)
}
}
}
# ----------------------------------------------------------------------------------------------------------------
function add-depitem($lbitem, $color, $resourceGroup)
{
try
{
[Windows.Controls.ListBoxItem]$lbi = new-object Windows.Controls.ListBoxItem
$lbi.Background = $color
$failed = $false
$state = $lbitem.ProvisioningState
if ([string]::IsNullOrEmpty($state))
{
$state = $lbitem.Properties.ProvisioningState
}
$operation = $lbitem.ProvisioningOperation
if ([string]::IsNullOrEmpty($operation))
{
$operation = $lbitem.Properties.ProvisioningOperation
}
if ($state -imatch "Failed")
{
$lbi.Background = "Red"
$failed = $true
}
elseif ($state -imatch "Succeeded" -and $operation -imatch "EvaluateDeploymentOutput")
{
$lbi.Background = "Chartreuse"
}
elseif ($state -imatch "Succeeded")
{
$lbi.Background = "YellowGreen"
}
elseif ($state -imatch "Started")
{
$lbi.Background = "LightGreen"
}
elseif ($state -imatch "Completed")
{
$lbi.Background = "Gray"
}
$lbi.Content = "$((get-localTime -time (get-time -item $lbitem)))" `
+ " DEPLOYMENT: $($resourceGroup)" `
+ " $($lbItem.DeploymentName)" `
+ " $($state)" `
+ " $($operation)" `
+ " $($lbitem.Properties.TargetResource.resourceType)" `
+ " $($lbitem.Properties.TargetResource.resourceName)" `
+ " $($lbitem.Output)"
if (!$global:index.ContainsKey((get-time -item $lbitem)))
{
if ($detail)
{
if ($failed)
{
write-host $lbi.Content -BackgroundColor Red
}
else
{
write-host $lbi.Content -BackgroundColor Green
}
}
$lbi.Tag = $lbitem
$ret = $global:listbox.Items.Insert(0, $lbi)
$global:index.Add((get-time -item $lbitem), $($lbitem.CorrelationId))
}
else
{
if ($detail)
{
write-host "$(($item | out-string)) exists"
}
}
}
catch
{
write-host "add-depitem:exception:$($error | out-string)`r`n$($psitem.ScriptStackTrace)"
$error.Clear()
}
}
# ----------------------------------------------------------------------------------------------------------------
function add-eventItem($lbitem, $color)
{
[Windows.Controls.ListBoxItem]$lbi = new-object Windows.Controls.ListBoxItem
$lbi.Background = $color
$failed = $false
if ($lbitem.Status -imatch "Fail")
{
$lbi.Background = "Red"
$failed = $true
}
elseif ($lbitem.Status -imatch "Succeeded")
{
$lbi.Background = "LightBlue"
if ($lbitem.OperationName -imatch "delete")
{
$lbi.Background = "DarkGray"
}
}
elseif ($lbitem.Status -imatch "Started")
{
$lbi.Background = "LightGreen"
}
elseif ($lbitem.Status -imatch "Completed")
{
$lbi.Background = "Gray"
}
$statusCode = [string]::Empty
if ([regex]::IsMatch($lbitem.Properties.ToString(), "statusCode.\W+:\W+(.+)"), [Text.RegularExpressions.RegexOptions]::IgnoreCase)
{
$statusCode = [string](([regex]::Match($lbitem.Properties.ToString(), "statusCode.\W+:\W+(.+)", [Text.RegularExpressions.RegexOptions]::IgnoreCase)).Groups[1].Value).Trim()
}
$statusMessage = [string]::Empty
if ([regex]::IsMatch($lbitem.Properties.ToString(), "statusMessage.\W+:\W+`"(.+)`""), [Text.RegularExpressions.RegexOptions]::IgnoreCase)
{
$statusMessage = [string](([regex]::Match($lbitem.Properties.ToString(), "statusMessage.\W+:\W+`"(.+)`"", [Text.RegularExpressions.RegexOptions]::IgnoreCase)).Groups[1].Value).Trim()
}
if ($lbitem.Properties.Content.statusMessage -ne $null)
{
$statusMessage = $lbitem.Properties.Content.statusMessage
}
# take first two directories from operationname and use to find additional information in resourceid
$opNameBase = [string]::Empty
if ([regex]::IsMatch($lbitem.OperationName, '^(.+?/.+?)/', [Text.RegularExpressions.RegexOptions]::IgnoreCase))
{
$opNameBase = ([regex]::Match($lbitem.OperationName, '^(.+?/.+?)/')).Groups[1].Value
}
$resourcePath = [string]::Empty
if ([regex]::IsMatch($lbitem.ResourceId, $opNameBase, [Text.RegularExpressions.RegexOptions]::IgnoreCase))
{
$resourcePath = ([regex]::Match($lbitem.ResourceId, "($($opNameBase).+)")).Groups[1].Value
}
else
{
$resourcePath = [IO.Path]::GetFileName($lbitem.ResourceId)
}
$lbi.Content = "$((get-localTime -time (get-time -item $lbitem)))" `
+ " EVENT: $($lbitem.ResourceGroupName)" `
+ " $($lbitem.Status)" `
+ " $($lbitem.SubStatus)" `
+ " STATUS: $($statusCode)" `
+ " MESSAGE: $($statusMessage)" `
+ " $($resourcePath)"
if ($lbItem.EventDataId -eq $null -or !$global:index.ContainsKey((get-time -item $lbitem)))
{
if ($detail)
{
if ($failed)
{
write-host $lbi.Content -BackgroundColor Red
}
else
{
write-host $lbi.Content -BackgroundColor Green
}
}
if ($lbitem.EventTimeStamp -gt $global:eventStartTime)
{
$global:eventStartTime = $lbitem.EventTimeStamp
}
$lbi.Tag = $lbitem
$ret = $global:listbox.Items.Insert(0, $lbi)
$global:index.Add((get-time -item $lbitem), $($lbitem.CorrelationId))
}
else
{
if ($detail)
{
write-host "$(($item | out-string)) exists"
}
}
}
# ----------------------------------------------------------------------------------------------------------------
function authenticate-az($context = $Null)
{
if ($context)
{
$ctx = $null
$ctx = Import-azContext -Path $context
# bug to be fixed 8/2017
# From <https://github.com/Azure/azure-powershell/issues/3954>
[void]$ctx.Context.TokenCache.Deserialize($ctx.Context.TokenCache.CacheData)
return $true
}
# make sure at least wmf 5.0 installed
if ($PSVersionTable.PSVersion -lt [version]"5.0.0.0")
{
write-host "update version of powershell to at least wmf 5.0. exiting..." -ForegroundColor Yellow
start-process "https://www.bing.com/search?q=download+windows+management+framework+5.0"
# start-process "https://www.microsoft.com/en-us/download/details.aspx?id=50395"
exit
}
# verify NuGet package
$nuget = get-packageprovider nuget -Force
if (-not $nuget -or ($nuget.Version -lt [version]::New("2.8.5.22")))
{
write-host "installing nuget package..."
install-packageprovider -name NuGet -minimumversion ([version]::New("2.8.5.201")) -force
}
$allModules = (get-module az* -ListAvailable).Name
# install az module
if ($allModules -inotcontains "az")
{
# at least need profile, resources, insights, logicapp
if ($allModules -inotcontains "az.accounts")
{
write-host "installing az.accounts powershell module..."
install-module az.accounts -force
}
if ($allModules -inotcontains "az.resources")
{
write-host "installing az.resources powershell module..."
install-module az.resources -force
}
if ($allModules -inotcontains "az.insights")
{
write-host "installing az.insights powershell module..."
install-module az.insights -force
}
if ($allModules -inotcontains "az.logicapp")
{
write-host "installing az.logicapp powershell module..."
install-module az.logicapp -force
}
Import-Module az.accounts
Import-Module az.resources
Import-Module az.insights
Import-Module az.logicapp
#write-host "installing az powershell module..."
#install-module az -force
}
else
{
Import-Module az
}
# authenticate
try
{
$rg = @(Get-azResourceGroup)
if ($rg)
{
write-host "job:auth passed $($rg.Count)"
}
else
{
write-host "job:auth error $($error | out-string)" -ForegroundColor Yellow
throw [Exception]
}
}
catch
{
try
{
connect-azaccount
}
catch
{
write-host "exception authenticating. exiting $($error | out-string)`r`n$($psitem.ScriptStackTrace)" -ForegroundColor Yellow
exit 1
}
}
Save-azContext -Path $profileContext -Force
}
# ----------------------------------------------------------------------------------------------------------------
function check-backgroundJob()
{
Write-Verbose "check-backgroundjob:enter"
$job = $null
if (!($job = get-job -Name $global:jobName -ErrorAction SilentlyContinue))
{
write-host "job does not exist: $($global:jobName)"
$job = start-backgroundJob
}
else
{
if ($detail)
{
write-host "job exists: $($global:jobName)"
}
}
if ($job.State -ine "Running")
{
write-host "job state: $($job.State)"
$job = start-backgroundJob
}
if ($detail)
{
write-host "job state: $($job.State)"
}
}
# ----------------------------------------------------------------------------------------------------------------
function clear-list()
{
$global:listbox.Items.Clear()
$global:listboxEvent.Items.Clear()
$global:index.Clear()
#$global:eventStartTime = [DateTime]::Now.AddDays(-1)
}
# ----------------------------------------------------------------------------------------------------------------
function convert-localizableStrings($items)
{
# Microsoft.Azure.Management.Monitor.Models.LocalizableString
# PSEventData Microsoft.Azure.Management.Monitor.Models.EventData
$localizedItems = new-object Collections.ArrayList
foreach($item in $items)
{
$localizedItem = @{}
$localizedItem.Authorization = $item.Authorization
$localizedItem.Claims = $item.Claims
$localizedItem.Caller = $item.Caller
$localizedItem.Description = $item.Description
$localizedItem.Id = $item.Id
$localizedItem.EventDataId = $item.EventDataId
$localizedItem.CorrelationId = $item.CorrelationId
$localizedItem.EventName = $item.EventName.LocalizedValue
$localizedItem.Category = $item.Category.LocalizedValue
$localizedItem.HttpRequest = $item.HttpRequest
$localizedItem.Level = $item.Level
$localizedItem.ResourceGroupName = $item.ResourceGroupName
$localizedItem.ResourceProviderName = $item.ResourceProviderName.LocalizedValue
$localizedItem.ResourceId = $item.ResourceId
$localizedItem.ResourceType = $item.ResourceType
$localizedItem.OperationId = $item.OperationId
$localizedItem.OperationName = $item.OperationName.LocalizedValue
$localizedItem.Properties = $item.Properties
$localizedItem.Status = $item.Status.LocalizedValue
$localizedItem.SubStatus = $item.SubStatus.LocalizedValue
$localizedItem.EventTimestamp = $item.EventTimeStamp
$localizedItem.SubmissionTimestamp = $item.Timestamp
$localizedItem.SubscriptionId = $item.SubscriptionId
$localizedItem.TenantId = $item.TenantId
[void]$localizedItems.Add($localizedItem)
}
return $localizedItems
}
# ----------------------------------------------------------------------------------------------------------------
function do-backgroundJob($jobInfo)
{
# runs on background thread
$count = 0
while ($true)
{
write-host "doing background job $($jobInfo.action) event start time: $($jobInfo.eventStartTime)"
# for job debugging
# when attached with -debug switch, set $jobInfo.debugPreference to SilentlyContinue to debug
while ($jobInfo.debugPreference -imatch "Inquire")
{
write-host "waiting to debug background job $($jobInfo.action) : $($jobInfo.debugPreference)"
write-host "set jobInfo.debugPreference = SilentlyContinue to break debug loop"
start-sleep -Seconds 1
}
authenticate-az -context $jobInfo.profileContext
# set global start time from job
$global:eventStartTime = $jobInfo.eventStartTime
$global:resourcegroupUpdate = $global:eventStartTime
$global:deploymentUpdate = $global:eventStartTime
while ($true)
{
$jobResults = new-jobResults
try
{
# wait for command
if ($jobInfo.detail)
{
write-host "$([DateTime]::Now) job:running commands"
}
$error.clear()
$jobResults = run-commands -jobObject $jobResults
if ($jobInfo.detail)
{
write-host "$([DateTime]::Now) job:finished processing results count: $($jobResults.GroupOutput.Count):$($jobResults.DeploymentOutput.Count)"
write-host "results: $($jobResults | format-list * | out-string)"
}
# output result object
$jobResults
Start-Sleep -Seconds $global:refreshTime.Seconds
}
catch
{
$jobResults.LastResult = $error | out-string
$jobResults
$error.Clear()
#if(!authenticate-az)
#{
# return
#}
}
}
$jobInfo.result = $count
$jobInfo
Start-Sleep $global:refreshTime
$count++
}
}
# ----------------------------------------------------------------------------------------------------------------
function enum-deployments($resoureGroup = ".")
{
if (![string]::IsNullOrEmpty($deploymentname))
{
return ($global:deployments = @{$resoureGroup = @{$deploymentname = 0}})
}
if ([DateTime]::Now.AddMinutes( - $global:cacheMinutes) -gt [DateTime]$global:deploymentUpdate)
{
$global:deploymentUpdate = [DateTime]::Now
foreach ($group in (enum-resourceGroups).GetEnumerator())
{
$deployments = (Get-azResourceGroupDeployment -ResourceGroupName $($group.Key))
foreach ($deployment in $deployments)
{
if (!$global:deployments.ContainsKey($group.Key))
{
[void]$global:deployments.Add($group.Key, @{})
}
if ($deployment.TimeStamp -gt $global:eventStartTime)
{
if (!$global:deployments[$group.Key].ContainsKey($deployment.DeploymentName))
{
[void]$global:deployments[$group.Key].Add($deployment.DeploymentName, 0)
}
}
}
}
}
return ($global:deployments | Where-object Keys -imatch $resoureGroup).Values
}
# ----------------------------------------------------------------------------------------------------------------
function enum-resourceGroups()
{
$global:groups = @{}
if (![string]::IsNullOrEmpty($resourceGroupName))
{
[void]$global:groups.Add($resourcegroupname, 0)
return ($global:groups)
}
if ([DateTime]::Now.AddMinutes( - $global:cacheMinutes) -gt [DateTime]$global:resourcegroupUpdate)
{
$global:resourceGroupUpdate = [DateTime]::Now
$groups = (Get-azResourceGroup | Get-azResourceGroupDeployment | Where-Object TimeStamp -gt $($global:eventStartTime) | Select-Object ResourceGroupName -Unique)
if ($groups.Count -eq 0)
{
$groups = (Get-azResourceGroup | Select-Object ResourceGroupName -Unique)
}
foreach ($group in $groups)
{
[void]$global:groups.Add($group.ResourceGroupName, 0)
}
}
return $global:groups
}
# ----------------------------------------------------------------------------------------------------------------
function export-list()
{
[Windows.Input.Mouse]::SetCursor([Windows.Input.Cursors]::AppStarting)
[Text.StringBuilder]$sb = new-object Text.StringBuilder
$fileName = "$(get-location)\$([DateTime]::Now.ToString("yyyy-MM-dd-HH-mm"))-$($global:exportFile)"
if ([IO.File]::Exists($fileName))
{
write-host "deleting file $($fileName)"
[IO.File]::Delete($fileName)
}
$sb.AppendLine("{")
foreach ($item in $global:listbox.Items)
{
if ($detail)
{
write-host "exporting: $($item.Content)"
}
$sb.AppendLine("//----------------------------------------------------------------------------------------")
$sb.AppendLine("//$($item.Content.ToString().Trim())")
$sb.AppendLine("$(format-record -inputString ($item.Tag | ConvertTo-Json -Depth 100)),")
}
out-file -Append -InputObject "$($sb.ToString().Trim(","))}" -FilePath $fileName
write-host "finished exporting to: $([IO.Path]::GetFullPath($fileName))"
start-process $fileName
[Windows.Input.Mouse]::SetCursor([Windows.Input.Cursors]::Arrow)
}
# ----------------------------------------------------------------------------------------------------------------
function format-eventView($item, $listBoxItem)
{
if (($item | format-list | out-string) -imatch "(level\:.+[1-2])|(provisioningstate\:.+failed)|(status\:.+failed)|(failed)")
{
$listBoxItem.Background = "AliceBlue"
$listBoxItem.Foreground = "Red"
if ($detail)
{
write-host ($item | format-list * | out-string) -BackgroundColor Red
}
}
else
{
$listBoxItem.Background = "AliceBlue"
$listBoxItem.Foreground = "Green"
if ($detail)
{
write-host ($item | format-list * | out-string) -BackgroundColor Green
}
}
return $listBoxItem
}
# ----------------------------------------------------------------------------------------------------------------
function format-record([string]$inputString)
{
#get rid of in order:
# \u0027 unicode value for "'" single tick and replace with single tick '
# \" literal
# " literal
# new line literals and replace with new line tab tab
# { and replace with { new line tab tab
# } and replace with } new line tab tab
# , new line and replace with new line
# , and replace with new line tab tab
return ((($inputString).Replace("\u0027", "'").Replace("\`"", "").Replace("`"", "").Replace("\r\n", "`r`n`t`t").Replace("{", "{`r`n`t`t").Replace("}", "`r`n`t`t}") -replace ",`r`n", "`r`n") -replace ",", "`r`n`t`t")
}
# ----------------------------------------------------------------------------------------------------------------
function get-localTime([string]$time)
{
if (![string]::IsNullOrEmpty($time))
{
$time = $time.Replace("Z", "")
return [System.TimeZoneInfo]::ConvertTimeFromUtc($time, [System.TimeZoneInfo]::Local).ToString("o")
}
return $null
}
# ----------------------------------------------------------------------------------------------------------------
function get-subscriptions()
{
write-host "enumerating subscriptions"
$subList = @{}
$subs = Get-azSubscription -WarningAction SilentlyContinue
$newSubFormat = (get-module az.Resources).Version.ToString() -ge "4.0.0"
if ($subs.Count -gt 1)
{
[int]$count = 1
foreach ($sub in $subs)
{
if ($newSubFormat)
{
$message = "$($count). $($sub.name) $($sub.id)"
$id = $sub.id
}
else
{
$message = "$($count). $($sub.SubscriptionName) $($sub.SubscriptionId)"
$id = $sub.SubscriptionId
}
write-host $message
[void]$subList.Add($count, $id)
$count++
}
[int]$id = Read-Host ("Enter number for subscription to enumerate or {enter} to query all:")
$null = Set-azContext -SubscriptionId $subList[$id].ToString()
}
return
}
# ----------------------------------------------------------------------------------------------------------------
function get-time($item)
{
$retVal = ($global:eventStartTime).ToString("o")
try
{
if ($item -eq $null)
{
return $retVal
}
if (($utcTime = $item.TimeStamp) -eq $null)
{
if (($utcTime = $item.EventTimeStamp) -eq $null)
{
if (($utcTime = $item.Properties.TimeStamp) -eq $null)
{
return $retVal
}
else
{
$utcTime = $item.Properties.TimeStamp
}
}
else
{
$utcTime = $item.EventTimeStamp
}
}
else
{
$utcTime = $item.TimeStamp
}
if ([string]::IsNullOrEmpty($utcTime) -or !([DateTime]::Parse($utcTime)))
{
write-host "get-time: returning start time"
return $retVal
}
try
{
$retVal = $utcTime.ToString("o")
}
catch
{
$error.clear()
return $utcTime
}
return $retVal
}
catch
{
write-host "exception:get-time $($error | out-string)`r`n$($psitem.ScriptStackTrace)"
$error.Clear()
return $retVal
}
}
# ----------------------------------------------------------------------------------------------------------------
function get-update($updateUrl, $destinationFile)
{
write-host "get-update:checking for updated script: $($updateUrl)"
try
{
$git = Invoke-RestMethod -Method Get -Uri $updateUrl
# git may not have carriage return
if ([regex]::Matches($git, "`r").Count -eq 0)
{
$git = [regex]::Replace($git, "`n", "`r`n")
}
if (![IO.File]::Exists($destinationFile))
{
$file = ""
}
else
{
$file = [IO.File]::ReadAllText($destinationFile)
}
if (([string]::Compare($git, $file) -ne 0))
{
write-host "copying script $($destinationFile)"