-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAzLogDcrIngestPS.psm1
6524 lines (5433 loc) · 355 KB
/
AzLogDcrIngestPS.psm1
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
Function Add-CollectionTimeToAllEntriesInArray
{
<#
.SYNOPSIS
Add property CollectionTime (based on current time) to all entries on the object
.DESCRIPTION
Gives capability to do proper searching in queries to find latest set of records with same collection time
Time Generated cannot be used when you are sending data in batches, as TimeGenerated will change
An example where this is important is a complete list of applications for a computer. We want all applications to
show up when queriying for the latest data
.PARAMETER Data
Object to modify
.INPUTS
None. You cannot pipe objects
.OUTPUTS
Updated object with CollectionTime
.LINK
https://github.com/KnudsenMorten/AzLogDcrIngestPS
.EXAMPLE
#-------------------------------------------------------------------------------------------
# Variables
#-------------------------------------------------------------------------------------------
$Verbose = $true # $true or $false
#-------------------------------------------------------------------------------------------
# Collecting data (in)
#-------------------------------------------------------------------------------------------
$DNSName = (Get-CimInstance win32_computersystem).DNSHostName +"." + (Get-CimInstance win32_computersystem).Domain
$ComputerName = (Get-CimInstance win32_computersystem).DNSHostName
[datetime]$CollectionTime = ( Get-date ([datetime]::Now.ToUniversalTime()) -format "yyyy-MM-ddTHH:mm:ssK" )
$UserLoggedOnRaw = Get-Process -IncludeUserName -Name explorer | Select-Object UserName -Unique
$UserLoggedOn = $UserLoggedOnRaw.UserName
$DataVariable = Get-CimInstance -ClassName Win32_Processor | Select-Object -ExcludeProperty "CIM*"
#-------------------------------------------------------------------------------------------
# Preparing data structure
#-------------------------------------------------------------------------------------------
$DataVariable = Convert-CimArrayToObjectFixStructure -data $DataVariable -Verbose:$Verbose
$DataVariable
# add CollectionTime to existing array
$DataVariable = Add-CollectionTimeToAllEntriesInArray -Data $DataVariable -Verbose:$Verbose
$DataVariable
#-------------------------------------------------------------------------------------------
# Output
#-------------------------------------------------------------------------------------------
VERBOSE: Adding CollectionTime to all entries in array .... please wait !
Caption : Intel64 Family 6 Model 165 Stepping 5
Description : Intel64 Family 6 Model 165 Stepping 5
InstallDate :
Name : Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
Status : OK
Availability : 3
ConfigManagerErrorCode :
ConfigManagerUserConfig :
CreationClassName : Win32_Processor
DeviceID : CPU0
ErrorCleared :
ErrorDescription :
LastErrorCode :
PNPDeviceID :
PowerManagementCapabilities :
PowerManagementSupported : False
StatusInfo : 3
SystemCreationClassName : Win32_ComputerSystem
SystemName : STRV-MOK-DT-02
AddressWidth : 64
CurrentClockSpeed : 2904
DataWidth : 64
Family : 198
LoadPercentage : 1
MaxClockSpeed : 2904
OtherFamilyDescription :
Role : CPU
Stepping :
UniqueId :
UpgradeMethod : 1
Architecture : 9
AssetTag : To Be Filled By O.E.M.
Characteristics : 252
CpuStatus : 1
CurrentVoltage : 8
ExtClock : 100
L2CacheSize : 2048
L2CacheSpeed :
L3CacheSize : 16384
L3CacheSpeed : 0
Level : 6
Manufacturer : GenuineIntel
NumberOfCores : 8
NumberOfEnabledCore : 8
NumberOfLogicalProcessors : 16
PartNumber : To Be Filled By O.E.M.
ProcessorId : BFEBFBFF000A0655
ProcessorType : 3
Revision :
SecondLevelAddressTranslationExtensions : False
SerialNumber : To Be Filled By O.E.M.
SocketDesignation : U3E1
ThreadCount : 16
Version :
VirtualizationFirmwareEnabled : False
VMMonitorModeExtensions : False
VoltageCaps :
PSComputerName :
CollectionTime : 12-03-2023 16:08:33
#>
[CmdletBinding()]
param(
[Parameter(mandatory)]
[Array]$Data
)
[datetime]$CollectionTime = ( Get-date ([datetime]::Now.ToUniversalTime()) -format "yyyy-MM-ddTHH:mm:ssK" )
Write-Verbose " Adding CollectionTime to all entries in array .... please wait !"
$IntermediateObj = @()
ForEach ($Entry in $Data)
{
$Entry | Add-Member -MemberType NoteProperty -Name CollectionTime -Value $CollectionTime -Force | Out-Null
$IntermediateObj += $Entry
}
return [array]$IntermediateObj
}
Function Add-ColumnDataToAllEntriesInArray
{
<#
.SYNOPSIS
Adds up to 3 extra columns and data to the object
.DESCRIPTION
Gives capability to extend the data with for example Computer and UserLoggedOn, which are nice data to have in the inventory
.PARAMETER Data
Object to modify
.PARAMETER Column1Name
Name of the column to add (for example Computer)
.PARAMETER Column1Data
Data to add to the column1 (for example $Env:Computer)
.PARAMETER Column2Name
Name of the column to add (for example UserLoggedOn)
.PARAMETER Column2Data
Data to add to the column1 (for example $UserLoggedOn)
.PARAMETER Column3Name
Name of the column to add (for example ComputerType)
.PARAMETER Column3Data
Data to add to the column1 (for example $ComputerType)
.INPUTS
None. You cannot pipe objects
.OUTPUTS
Updated object with CollectionTime
.LINK
https://github.com/KnudsenMorten/AzLogDcrIngestPS
.EXAMPLE
#-------------------------------------------------------------------------------------------
# Variables
#-------------------------------------------------------------------------------------------
$Verbose = $true # $true or $false
#-------------------------------------------------------------------------------------------
# Collecting data (in)
#-------------------------------------------------------------------------------------------
$DNSName = (Get-CimInstance win32_computersystem).DNSHostName +"." + (Get-CimInstance win32_computersystem).Domain
$ComputerName = (Get-CimInstance win32_computersystem).DNSHostName
[datetime]$CollectionTime = ( Get-date ([datetime]::Now.ToUniversalTime()) -format "yyyy-MM-ddTHH:mm:ssK" )
$UserLoggedOnRaw = Get-Process -IncludeUserName -Name explorer | Select-Object UserName -Unique
$UserLoggedOn = $UserLoggedOnRaw.UserName
$DataVariable = Get-CimInstance -ClassName Win32_Processor | Select-Object -ExcludeProperty "CIM*"
$DataVariable
#-------------------------------------------------------------------------------------------
# Preparing data structure
#-------------------------------------------------------------------------------------------
$DataVariable = Convert-CimArrayToObjectFixStructure -data $DataVariable -Verbose:$Verbose
$DataVariable
# add CollectionTime to existing array
$DataVariable = Add-CollectionTimeToAllEntriesInArray -Data $DataVariable -Verbose:$Verbose
$DataVariable
# add Computer & UserLoggedOn info to existing array
$DataVariable = Add-ColumnDataToAllEntriesInArray -Data $DataVariable -Column1Name Computer -Column1Data $ComputerName -Column2Name UserLoggedOn -Column2Data $UserLoggedOn -Verbose:$verbose
$DataVariable
#-------------------------------------------------------------------------------------------
# Output
#-------------------------------------------------------------------------------------------
Caption : Intel64 Family 6 Model 165 Stepping 5
Description : Intel64 Family 6 Model 165 Stepping 5
InstallDate :
Name : Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
Status : OK
Availability : 3
ConfigManagerErrorCode :
ConfigManagerUserConfig :
CreationClassName : Win32_Processor
DeviceID : CPU0
ErrorCleared :
ErrorDescription :
LastErrorCode :
PNPDeviceID :
PowerManagementCapabilities :
PowerManagementSupported : False
StatusInfo : 3
SystemCreationClassName : Win32_ComputerSystem
SystemName : STRV-MOK-DT-02
AddressWidth : 64
CurrentClockSpeed : 2904
DataWidth : 64
Family : 198
LoadPercentage : 1
MaxClockSpeed : 2904
OtherFamilyDescription :
Role : CPU
Stepping :
UniqueId :
UpgradeMethod : 1
Architecture : 9
AssetTag : To Be Filled By O.E.M.
Characteristics : 252
CpuStatus : 1
CurrentVoltage : 8
ExtClock : 100
L2CacheSize : 2048
L2CacheSpeed :
L3CacheSize : 16384
L3CacheSpeed : 0
Level : 6
Manufacturer : GenuineIntel
NumberOfCores : 8
NumberOfEnabledCore : 8
NumberOfLogicalProcessors : 16
PartNumber : To Be Filled By O.E.M.
ProcessorId : BFEBFBFF000A0655
ProcessorType : 3
Revision :
SecondLevelAddressTranslationExtensions : False
SerialNumber : To Be Filled By O.E.M.
SocketDesignation : U3E1
ThreadCount : 16
Version :
VirtualizationFirmwareEnabled : False
VMMonitorModeExtensions : False
VoltageCaps :
PSComputerName :
CollectionTime : 12-03-2023 16:19:12
Computer : STRV-MOK-DT-02
UserLoggedOn : 2LINKIT\mok#>
#>
[CmdletBinding()]
param(
[Parameter(mandatory)]
[Array]$Data,
[Parameter(mandatory)]
[string]$Column1Name,
[Parameter(mandatory)]
[string]$Column1Data,
[Parameter()]
[string]$Column2Name,
[Parameter()]
[string]$Column2Data,
[Parameter()]
[string]$Column3Name,
[Parameter()]
[string]$Column3Data
)
Write-Verbose " Adding columns to all entries in array .... please wait !"
$IntermediateObj = @()
ForEach ($Entry in $Data)
{
If ($Column1Name)
{
$Entry | Add-Member -MemberType NoteProperty -Name $Column1Name -Value $Column1Data -Force
}
If ($Column2Name)
{
$Entry | Add-Member -MemberType NoteProperty -Name $Column2Name -Value $Column2Data -Force
}
If ($Column3Name)
{
$Entry | Add-Member -MemberType NoteProperty -Name $Column3Name -Value $Column3Data -Force
}
$IntermediateObj += $Entry
}
return [array]$IntermediateObj
}
Function Build-DataArrayToAlignWithSchema
{
<#
.SYNOPSIS
Rebuilds the source object to match modified schema structure - used after usage of ValidateFix-AzLogAnalyticsTableSchemaColumnNames
.DESCRIPTION
Builds new PSCustomObject object
.PARAMETER Data
This is the data array
.INPUTS
None. You cannot pipe objects
.OUTPUTS
Updated $DataVariable with valid column names
.LINK
https://github.com/KnudsenMorten/AzLogDcrIngestPS
.EXAMPLE
#-------------------------------------------------------------------------------------------
# Collecting data (in)
#-------------------------------------------------------------------------------------------
$DNSName = (Get-CimInstance win32_computersystem).DNSHostName +"." + (Get-CimInstance win32_computersystem).Domain
$ComputerName = (Get-CimInstance win32_computersystem).DNSHostName
[datetime]$CollectionTime = ( Get-date ([datetime]::Now.ToUniversalTime()) -format "yyyy-MM-ddTHH:mm:ssK" )
$UserLoggedOnRaw = Get-Process -IncludeUserName -Name explorer | Select-Object UserName -Unique
$UserLoggedOn = $UserLoggedOnRaw.UserName
Write-Output "Get-Process is pretty slow .... take a cup coffee :-)"
$DataVariable = Get-Process
#-------------------------------------------------------------------------------------------
# Preparing data structure
#-------------------------------------------------------------------------------------------
# convert CIM array to PSCustomObject and remove CIM class information
$DataVariable = Convert-CimArrayToObjectFixStructure -data $DataVariable -Verbose:$Verbose
# add CollectionTime to existing array
$DataVariable = Add-CollectionTimeToAllEntriesInArray -Data $DataVariable -Verbose:$Verbose
# add Computer & UserLoggedOn info to existing array
$DataVariable = Add-ColumnDataToAllEntriesInArray -Data $DataVariable -Column1Name Computer -Column1Data $Env:ComputerName -Column2Name UserLoggedOn -Column2Data $UserLoggedOn -Verbose:$Verbose
# adding prohibted columns to data - to demonstrate how it works
$DataVariable = Add-ColumnDataToAllEntriesInArray -Data $DataVariable -Column1Name "Type" -Column1Data "MyDataType" -Verbose:$Verbose
$DataVariable = Add-ColumnDataToAllEntriesInArray -Data $DataVariable -Column1Name "Id" -Column1Data "MyId" -Verbose:$Verbose
# schema - before changes - we see columns named Type and Id (prohibited)
Get-ObjectSchemaAsArray -Data $DataVariable
# Data before changes - we see columns named Type and Id (prohibited)
$DataVariable[0]
# Validating/fixing schema data structure of source data
$DataVariable = ValidateFix-AzLogAnalyticsTableSchemaColumnNames -Data $DataVariable -Verbose:$Verbose
# schema - after changes - we see columns named Type has been renamed to Type_ and Id to Id_ (prohibited)
Get-ObjectSchemaAsArray -Data $DataVariable -Verbose:$Verbose
# Data after changes - we see data was transferred to new columns (type_ and id_ - and the wrong columns (type, id) were removed
$DataVariable[0]
# Aligning data structure with schema (requirement for DCR)
$DataVariable = Build-DataArrayToAlignWithSchema -Data $DataVariable -Verbose:$Verbose
$DataVariable[0]
#-------------------------------------------------------------------------------------------
# Output
#-------------------------------------------------------------------------------------------
VERBOSE: Aligning source object structure with schema ... Please Wait !
BasePriority : 8
CollectionTime : 12-03-2023 16:25:37
Company :
Computer : STRV-MOK-DT-02
Container :
CPU : 0,015625
Description :
EnableRaisingEvents : False
ExitCode :
ExitTime :
FileVersion :
Handle : 10044
HandleCount : 377
Handles : 377
HasExited : False
Id_ : MyId
MachineName : .
MainModule : @{ModuleName=AcrobatNotificationClient.exe; FileName=C:\Program Files\WindowsApps\AcrobatNotificationClient_
1.0.4.0_x86__e1rzdqpraam7r\AcrobatNotificationClient.exe; BaseAddress=6225920; ModuleMemorySize=438272; Entr
yPointAddress=6460140; FileVersionInfo=; Site=; Container=}
MainWindowHandle : 0
MainWindowTitle :
MaxWorkingSet : 1413120
MinWorkingSet : 204800
Modules : {@{ModuleName=AcrobatNotificationClient.exe; FileName=C:\Program Files\WindowsApps\AcrobatNotificationClient
_1.0.4.0_x86__e1rzdqpraam7r\AcrobatNotificationClient.exe; BaseAddress=6225920; ModuleMemorySize=438272; Ent
ryPointAddress=6460140; FileVersionInfo=; Site=; Container=}, @{ModuleName=ntdll.dll; FileName=C:\WINDOWS\SY
STEM32\ntdll.dll; BaseAddress=140715251924992; ModuleMemorySize=2179072; EntryPointAddress=0; FileVersionInf
o=; Site=; Container=}, @{ModuleName=wow64.dll; FileName=C:\WINDOWS\System32\wow64.dll; BaseAddress=14071524
5764608; ModuleMemorySize=356352; EntryPointAddress=140715245870880; FileVersionInfo=; Site=; Container=}, @
{ModuleName=wow64base.dll; FileName=C:\WINDOWS\System32\wow64base.dll; BaseAddress=140715221450752; ModuleMe
morySize=36864; EntryPointAddress=140715221454864; FileVersionInfo=; Site=; Container=}...}
Name : AcrobatNotificationClient
NonpagedSystemMemorySize : 23424
NonpagedSystemMemorySize64 : 23424
NounName :
NPM : 23424
PagedMemorySize : 10592256
PagedMemorySize64 : 10592256
PagedSystemMemorySize : 466384
PagedSystemMemorySize64 : 466384
Path : C:\Program Files\WindowsApps\AcrobatNotificationClient_1.0.4.0_x86__e1rzdqpraam7r\AcrobatNotificationClient.
exe
PeakPagedMemorySize : 11440128
PeakPagedMemorySize64 : 11440128
PeakVirtualMemorySize : 318820352
PeakVirtualMemorySize64 : 318820352
PeakWorkingSet : 39202816
PeakWorkingSet64 : 39202816
PM : 10592256
PriorityBoostEnabled : True
PriorityClass : 32
PrivateMemorySize : 10592256
PrivateMemorySize64 : 10592256
PrivilegedProcessorTime : @{Ticks=156250; Days=0; Hours=0; Milliseconds=15; Minutes=0; Seconds=0; TotalDays=1,80844907407407E-07; Tota
lHours=4,34027777777778E-06; TotalMilliseconds=15,625; TotalMinutes=0,00026041666666666666; TotalSeconds=0,0
15625}
ProcessName : AcrobatNotificationClient
ProcessorAffinity : 65535
Product :
ProductVersion :
Responding : True
SafeHandle : @{IsInvalid=False; IsClosed=False}
SessionId : 1
SI : 1
Site :
StandardError :
StandardInput :
StandardOutput :
StartInfo : @{Verb=; Arguments=; CreateNoWindow=False; EnvironmentVariables=System.Object[]; Environment=System.Object[]
; RedirectStandardInput=False; RedirectStandardOutput=False; RedirectStandardError=False; StandardErrorEncod
ing=; StandardOutputEncoding=; UseShellExecute=True; Verbs=System.Object[]; UserName=; Password=; PasswordIn
ClearText=; Domain=; LoadUserProfile=False; FileName=; WorkingDirectory=; ErrorDialog=False; ErrorDialogPare
ntHandle=0; WindowStyle=0}
StartTime : 08-03-2023 22:22:46
SynchronizingObject :
Threads : {@{BasePriority=8; CurrentPriority=8; Id=24524; PriorityBoostEnabled=True; PriorityLevel=0; PrivilegedProces
sorTime=; StartAddress=140715252309904; StartTime=08-03-2023 22:22:46; ThreadState=5; TotalProcessorTime=; U
serProcessorTime=; WaitReason=5; Site=; Container=}, @{BasePriority=8; CurrentPriority=9; Id=18836; Priority
BoostEnabled=True; PriorityLevel=0; PrivilegedProcessorTime=; StartAddress=140715252309904; StartTime=08-03-
2023 22:22:46; ThreadState=5; TotalProcessorTime=; UserProcessorTime=; WaitReason=5; Site=; Container=}, @{B
asePriority=8; CurrentPriority=8; Id=18608; PriorityBoostEnabled=True; PriorityLevel=0; PrivilegedProcessorT
ime=; StartAddress=140715252309904; StartTime=08-03-2023 22:22:46; ThreadState=5; TotalProcessorTime=; UserP
rocessorTime=; WaitReason=5; Site=; Container=}, @{BasePriority=8; CurrentPriority=9; Id=18832; PriorityBoos
tEnabled=True; PriorityLevel=0; PrivilegedProcessorTime=; StartAddress=140715252309904; StartTime=08-03-2023
22:22:46; ThreadState=5; TotalProcessorTime=; UserProcessorTime=; WaitReason=5; Site=; Container=}...}
TotalProcessorTime : @{Ticks=156250; Days=0; Hours=0; Milliseconds=15; Minutes=0; Seconds=0; TotalDays=1,80844907407407E-07; Tota
lHours=4,34027777777778E-06; TotalMilliseconds=15,625; TotalMinutes=0,00026041666666666666; TotalSeconds=0,0
15625}
Type_ : MyDataType
UserLoggedOn : 2LINKIT\mok
UserProcessorTime : @{Ticks=0; Days=0; Hours=0; Milliseconds=0; Minutes=0; Seconds=0; TotalDays=0; TotalHours=0; TotalMillisecon
ds=0; TotalMinutes=0; TotalSeconds=0}
VirtualMemorySize : 289554432
VirtualMemorySize64 : 289554432
VM : 289554432
WorkingSet : 6758400
WorkingSet64 : 6758400
WS : 6758400
#>
[CmdletBinding()]
param(
[Parameter(mandatory)]
[Array]$Data
)
Write-Verbose " Aligning source object structure with schema ... Please Wait !"
# Get schema
$Schema = Get-ObjectSchemaAsArray -Data $Data -Verbose:$Verbose
$DataCount = ($Data | Measure-Object).Count
$DataVariableQA = @()
$Data | ForEach-Object -Begin {
$i = 0
} -Process {
# get column names
# $ObjColumns = $_ | Get-Member -MemberType NoteProperty
# enum schema
ForEach ($Column in $Schema)
{
# get column name & data
$ColumnName = $Column.Name
$ColumnData = $_.$ColumnName
$_ | Add-Member -MemberType NoteProperty -Name $ColumnName -Value $ColumnData -Force
}
$DataVariableQA += $_
# Increment the $i counter variable which is used to create the progress bar.
$i = $i+1
# Determine the completion percentage
$Completed = ($i/$DataCount) * 100
Write-Progress -Activity "Aligning source object structure with schema" -Status "Progress:" -PercentComplete $Completed
} -End {
Write-Progress -Activity "Aligning source object structure with schema" -Status "Ready" -Completed
# return data from temporary array to original $Data
$Data = $DataVariableQA
}
Return $Data
}
Function CheckCreateUpdate-TableDcr-Structure
{
<#
.SYNOPSIS
Create or Update Azure Data Collection Rule (DCR) used for log ingestion to Azure LogAnalytics using Log Ingestion API (combined)
.DESCRIPTION
Combined function which will combine 3 functions in one call:
Get-AzLogAnalyticsTableAzDataCollectionRuleStatus
CreateUpdate-AzLogAnalyticsCustomLogTableDcr
CreateUpdate-AzDataCollectionRuleLogIngestCustomLog
.AUTHOR
Morten Knudsen, Microsoft MVP - https://mortenknudsen.net
.LINK
https://github.com/KnudsenMorten/AzLogDcrIngestPS
.PARAMETER Data
Data object
.PARAMETER Tablename
Specifies the table name in LogAnalytics
.PARAMETER SchemaSourceObject
This is the schema in hash table format coming from the source object
.PARAMETER SchemaMode
SchemaMode = Merge (default)
It will do a merge/union of new properties and existing schema properties. DCR will import schema from table
SchemaMode = Overwrite
It will overwrite existing schema in DCR/table based on source object schema
This parameter can be useful for separate overflow work
.PARAMETER EnableUploadViaLogHub
$false = send logs directly to Azure, $true = send via remote path (log-hub), where log-engine will process data and upload. Made for legacy OS with TLS 1.0/1.1, PSVersion < 5.1
.PARAMETER AzLogWorkspaceResourceId
This is the Loganaytics Resource Id
.PARAMETER DceName
This is name of the Data Collection Endpoint to use for the upload
Function will automatically look check in a global variable ($global:AzDceDetails) - or do a query using Azure Resource Graph to find DCE with name
Goal is to find the log ingestion Uri on the DCE
Variable $global:AzDceDetails can be build before calling this cmdlet using this syntax
$global:AzDceDetails = Get-AzDceListAll -AzAppId $LogIngestAppId -AzAppSecret $LogIngestAppSecret -TenantId $TenantId -Verbose:$Verbose -Verbose:$Verbose
.PARAMETER DcrName
This is name of the Data Collection Rule to use for the upload
Function will automatically look check in a global variable ($global:AzDcrDetails) - or do a query using Azure Resource Graph to find DCR with name
Goal is to find the DCR immunetable id on the DCR
.PARAMETER DcrResourceGroup
This is name of the resource group, where Data Collection Rules will be stored
Variable $global:AzDcrDetails can be build before calling this cmdlet using this syntax
$global:AzDcrDetails = Get-AzDcrListAll -AzAppId $LogIngestAppId -AzAppSecret $LogIngestAppSecret -TenantId $TenantId -Verbose:$Verbose -Verbose:$Verbose
.PARAMETER TableName
This is tablename of the LogAnalytics table (and is also used in the DCR naming)
.PARAMETER AzDcrSetLogIngestApiAppPermissionsDcrLevel
Choose TRUE if you want to set Monitoring Publishing Contributor permissions on DCR level
Choose FALSE if you would like to use inherited permissions from the resource group level (recommended)
.PARAMETER LogIngestServicePricipleObjectId
This is the object id of the Azure App service-principal
NOTE: Not the object id of the Azure app, but Object Id of the service principal (!)
.PARAMETER AzLogDcrTableCreateFromReferenceMachine
Array with list of computers, where schema management can be done
.PARAMETER AzLogDcrTableCreateFromAnyMachine
True means schema changes can be made from any computer - FALSE means it can only happen from reference machine(s)
.PARAMETER AzAppId
This is the Azure app id
.PARAMETER AzAppSecret
This is the secret of the Azure app
.PARAMETER TenantId
This is the Azure AD tenant id
.INPUTS
None. You cannot pipe objects
.OUTPUTS
Output of REST PUT command. Should be 200 for success
.EXAMPLE
#-------------------------------------------------------------------------------------------
# Variables
#-------------------------------------------------------------------------------------------
$TableName = 'InvClientComputerOSInfoTest4V2' # must not contain _CL
$DcrName = "dcr-" + $AzDcrPrefixClient + "-" + $TableName + "_CL"
$TenantId = "xxxxx"
$LogIngestAppId = "xxxxx"
$LogIngestAppSecret = "xxxxx"
$DceName = "dce-log-platform-management-client-demo1-p"
$LogAnalyticsWorkspaceResourceId = "/subscriptions/xxxxxx/resourceGroups/rg-logworkspaces/providers/Microsoft.OperationalInsights/workspaces/log-platform-management-client-demo1-p"
$AzDcrPrefixClient = "clt1"
$AzDcrSetLogIngestApiAppPermissionsDcrLevel = $false
$AzDcrLogIngestServicePrincipalObjectId = "xxxxxx"
$AzLogDcrTableCreateFromReferenceMachine = @()
$AzLogDcrTableCreateFromAnyMachine = $true
# building global variable with all DCEs, which can be viewed by Log Ingestion app
$global:AzDceDetails = Get-AzDceListAll -AzAppId $LogIngestAppId -AzAppSecret $LogIngestAppSecret -TenantId $TenantId -Verbose:$Verbose
# building global variable with all DCRs, which can be viewed by Log Ingestion app
$global:AzDcrDetails = Get-AzDcrListAll -AzAppId $LogIngestAppId -AzAppSecret $LogIngestAppSecret -TenantId $TenantId -Verbose:$Verbose
#-------------------------------------------------------------------------------------------
# Collecting data (in)
#-------------------------------------------------------------------------------------------
Write-Output ""
Write-Output "Collecting OS information"
$DataVariable = Get-CimInstance -ClassName Win32_OperatingSystem
#-------------------------------------------------------------------------------------------
# Preparing data structure
#-------------------------------------------------------------------------------------------
# convert CIM array to PSCustomObject and remove CIM class information
$DataVariable = Convert-CimArrayToObjectFixStructure -data $DataVariable
# add CollectionTime to existing array
$DataVariable = Add-CollectionTimeToAllEntriesInArray -Data $DataVariable
# add Computer & UserLoggedOn info to existing array
$DataVariable = Add-ColumnDataToAllEntriesInArray -Data $DataVariable -Column1Name Computer -Column1Data $Env:ComputerName -Column2Name UserLoggedOn -Column2Data $UserLoggedOn
# Validating/fixing schema data structure of source data
$DataVariable = ValidateFix-AzLogAnalyticsTableSchemaColumnNames -Data $DataVariable
# Aligning data structure with schema (requirement for DCR)
$DataVariable = Build-DataArrayToAlignWithSchema -Data $DataVariable
#-------------------------------------------------------------------------------------------
# Create/Update Schema for LogAnalytics Table & Data Collection Rule schema
#-------------------------------------------------------------------------------------------
CheckCreateUpdate-TableDcr-Structure -AzLogWorkspaceResourceId $LogAnalyticsWorkspaceResourceId `
-AzAppId $LogIngestAppId -AzAppSecret $LogIngestAppSecret -TenantId $TenantId `
-DceName $DceName -DcrName $DcrName -TableName $TableName -Data $DataVariable `
-LogIngestServicePricipleObjectId $AzDcrLogIngestServicePrincipalObjectId `
-AzDcrSetLogIngestApiAppPermissionsDcrLevel $AzDcrSetLogIngestApiAppPermissionsDcrLevel `
-AzLogDcrTableCreateFromAnyMachine $AzLogDcrTableCreateFromAnyMachine `
-AzLogDcrTableCreateFromReferenceMachine $AzLogDcrTableCreateFromReferenceMachine
#-------------------------------------------------------------------------------------------
# Output
#-------------------------------------------------------------------------------------------
Collecting OS information
VERBOSE: Checking LogAnalytics table and Data Collection Rule configuration .... Please Wait !
VERBOSE: POST with -1-byte payload
VERBOSE: received 1468-byte response of content type application/json; charset=utf-8
VERBOSE: GET with 0-byte payload
VERBOSE: LogAnalytics table wasn't found !
VERBOSE: DCR was not found [ dcr-clt1-InvClientComputerOSInfoTest4V2_CL ]
VERBOSE: POST with -1-byte payload
VERBOSE: received 1468-byte response of content type application/json; charset=utf-8
VERBOSE:
VERBOSE: Trying to update existing LogAnalytics table schema for table [ InvClientComputerOSInfoTest4V2_CL ] in
VERBOSE: /subscriptions/fce4f282-fcc6-43fb-94d8-bf1701b862c3/resourceGroups/rg-logworkspaces/providers/Microsoft.OperationalInsights/works
paces/log-platform-management-client-demo1-p
VERBOSE: PATCH with -1-byte payload
VERBOSE: PUT with -1-byte payload
VERBOSE: received 7764-byte response of content type application/json; charset=utf-8
VERBOSE:
VERBOSE: LogAnalytics Table doesn't exist or problems detected .... creating table [ InvClientComputerOSInfoTest4V2_CL ] in
VERBOSE: /subscriptions/fce4f282-fcc6-43fb-94d8-bf1701b862c3/resourceGroups/rg-logworkspaces/providers/Microsoft.OperationalInsights/works
paces/log-platform-management-client-demo1-p
VERBOSE: PUT with -1-byte payload
VERBOSE: received 7764-byte response of content type application/json; charset=utf-8
StatusCode : 200
StatusDescription : OK
Content : {"properties":{"totalRetentionInDays":30,"archiveRetentionInDays":0,"plan":"Analytics","retentionInDaysAsDefault":tru
e,"totalRetentionInDaysAsDefault":true,"schema":{"tableSubType":"DataCollectionRule...
RawContent : HTTP/1.1 200 OK
Pragma: no-cache
Request-Context: appId=cid-v1:c7ec48f5-2684-46e8-accb-45e7dbec242b
X-Content-Type-Options: nosniff
api-supported-versions: 2015-03-20, 2015-11-01-preview, 2017-01-...
Forms : {}
Headers : {[Pragma, no-cache], [Request-Context, appId=cid-v1:c7ec48f5-2684-46e8-accb-45e7dbec242b], [X-Content-Type-Options, n
osniff], [api-supported-versions, 2015-03-20, 2015-11-01-preview, 2017-01-01-preview, 2017-03-03-preview, 2017-03-15-
preview, 2017-04-26-preview, 2020-03-01-preview, 2020-08-01, 2020-10-01, 2021-03-01-privatepreview, 2021-07-01-privat
epreview, 2021-12-01-preview, 2022-09-01-privatepreview, 2022-10-01]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 7764
VERBOSE: POST with -1-byte payload
VERBOSE: received 1468-byte response of content type application/json; charset=utf-8
VERBOSE: POST with -1-byte payload
VERBOSE: received 1342-byte response of content type application/json; charset=utf-8
VERBOSE: Found required DCE info using Azure Resource Graph
VERBOSE:
VERBOSE: GET with 0-byte payload
VERBOSE: received 898-byte response of content type application/json; charset=utf-8
VERBOSE: Found required LogAnalytics info
VERBOSE:
VERBOSE: GET with 0-byte payload
VERBOSE: received 291-byte response of content type application/json; charset=utf-8
VERBOSE:
VERBOSE: Creating/updating DCR [ dcr-clt1-InvClientComputerOSInfoTest4V2_CL ] with limited payload
VERBOSE: /subscriptions/fce4f282-fcc6-43fb-94d8-bf1701b862c3/resourceGroups/rg-dcr-log-platform-management-client-demo1-p/providers/micros
oft.insights/dataCollectionRules/dcr-clt1-InvClientComputerOSInfoTest4V2_CL
VERBOSE: PUT with -1-byte payload
VERBOSE: received 2094-byte response of content type application/json; charset=utf-8
StatusCode : 200
StatusDescription : OK
Content : {"properties":{"immutableId":"dcr-3433400ee8ca4570b606a9a21f2eea79","dataCollectionEndpointId":"/subscriptions/fce4f2
82-fcc6-43fb-94d8-bf1701b862c3/resourceGroups/rg-dce-log-platform-management-client...
RawContent : HTTP/1.1 200 OK
Pragma: no-cache
Vary: Accept-Encoding
x-ms-ratelimit-remaining-subscription-resource-requests: 149
Request-Context: appId=cid-v1:2bbfbac8-e1b0-44af-b9c6-3a40669d37e3
x-ms-correla...
Forms : {}
Headers : {[Pragma, no-cache], [Vary, Accept-Encoding], [x-ms-ratelimit-remaining-subscription-resource-requests, 149], [Reques
t-Context, appId=cid-v1:2bbfbac8-e1b0-44af-b9c6-3a40669d37e3]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 2094
VERBOSE:
VERBOSE: Updating DCR [ dcr-clt1-InvClientComputerOSInfoTest4V2_CL ] with full schema
VERBOSE: /subscriptions/fce4f282-fcc6-43fb-94d8-bf1701b862c3/resourceGroups/rg-dcr-log-platform-management-client-demo1-p/providers/micros
oft.insights/dataCollectionRules/dcr-clt1-InvClientComputerOSInfoTest4V2_CL
VERBOSE: PUT with -1-byte payload
VERBOSE: received 4546-byte response of content type application/json; charset=utf-8
StatusCode : 200
StatusDescription : OK
Content : {"properties":{"immutableId":"dcr-3433400ee8ca4570b606a9a21f2eea79","dataCollectionEndpointId":"/subscriptions/fce4f2
82-fcc6-43fb-94d8-bf1701b862c3/resourceGroups/rg-dce-log-platform-management-client...
RawContent : HTTP/1.1 200 OK
Pragma: no-cache
Vary: Accept-Encoding
x-ms-ratelimit-remaining-subscription-resource-requests: 148
Request-Context: appId=cid-v1:2bbfbac8-e1b0-44af-b9c6-3a40669d37e3
x-ms-correla...
Forms : {}
Headers : {[Pragma, no-cache], [Vary, Accept-Encoding], [x-ms-ratelimit-remaining-subscription-resource-requests, 148], [Reques
t-Context, appId=cid-v1:2bbfbac8-e1b0-44af-b9c6-3a40669d37e3]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 4546
VERBOSE:
VERBOSE: Waiting 10 sec to let Azure sync up so DCR rule can be retrieved from Azure Resource Graph
VERBOSE:
VERBOSE: Getting Data Collection Rules from Azure Resource Graph .... Please Wait !
VERBOSE: POST with -1-byte payload
VERBOSE: received 1468-byte response of content type application/json; charset=utf-8
VERBOSE: POST with -1-byte payload
VERBOSE: received 104224-byte response of content type application/json; charset=utf-8
#>
[CmdletBinding()]
param(
[Parameter(mandatory)]
[Array]$Data,
[Parameter(mandatory)]
[string]$AzLogWorkspaceResourceId,
[Parameter(mandatory)]
[string]$TableName,
[Parameter(mandatory)]
[string]$DcrName,
[Parameter(mandatory)]
[string]$DcrResourceGroup,
[Parameter(mandatory)]
[string]$DceName,
[Parameter()]
[AllowEmptyCollection()]
[string]$LogIngestServicePricipleObjectId,
[Parameter(mandatory)]
[boolean]$AzDcrSetLogIngestApiAppPermissionsDcrLevel = $false,
[Parameter()]
[boolean]$AzLogDcrTableCreateFromAnyMachine,
[Parameter()]
[string]$SchemaMode = "Merge", # Merge = Merge new properties into existing schema, Overwrite = use source object schema
[Parameter()]
[boolean]$EnableUploadViaLogHub = $false,
[Parameter(mandatory)]
[AllowEmptyCollection()]
[array]$AzLogDcrTableCreateFromReferenceMachine,
[Parameter()]
[string]$AzAppId,
[Parameter()]
[string]$AzAppSecret,
[Parameter()]
[string]$TenantId
)
#-------------------------------------------------------------------------------------------
# Create/Update Schema for LogAnalytics Table & Data Collection Rule schema
#-------------------------------------------------------------------------------------------
# default
$IssuesFound = $false
# Check for prohibited table names
If ($TableName -like "_*") # remove any leading underscores - column in DCR/LA must start with a character
{
$IssuesFound = $true
Write-Verbose ""
Write-Verbose " ISSUE - Table name must start with character [ $($TableName) ]"
Write-Verbose ""
}
ElseIf ($TableName -like "*-*") # includes - (hyphen)
{
$IssuesFound = $true
Write-Verbose ""
Write-Verbose " ISSUE - Table name include - (hyphen) - must be removed [ $($TableName) ]"
Write-Verbose ""
}
ElseIf ($TableName -like "*:*") # includes : (semicolon)
{
$IssuesFound = $true
Write-Verbose ""
Write-Verbose " ISSUE - Table name include : (semicolon) - must be removed [ $($TableName) ]"
Write-Verbose ""
}
ElseIf ($TableName -like "*.*") # includes . (period)
{
$IssuesFound = $true
Write-Verbose ""
Write-Verbose " ISSUE - Table name include . (period) - must be removed [ $($TableName) ]"
Write-Verbose ""
}
ElseIf ($TableName -like "* *") # includes whitespace " "
{
$IssuesFound = $true
Write-Verbose ""
Write-Verbose " ISSUE - Table name include whitespace - must be removed [ $($TableName) ]"
Write-Verbose ""
}
If ( ($EnableUploadViaLogHub -eq $false) -and ($IssuesFound -eq $false) )
{
If ( ($AzAppId) -and ($AzAppSecret) )
{
#-----------------------------------------------------------------------------------------------
# Check if table and DCR exist - or schema must be updated due to source object schema changes
#-----------------------------------------------------------------------------------------------
# Get insight about the schema structure
$Schema = Get-ObjectSchemaAsArray -Data $Data
$StructureCheck = Get-AzLogAnalyticsTableAzDataCollectionRuleStatus -AzLogWorkspaceResourceId $AzLogWorkspaceResourceId -TableName $TableName -DcrName $DcrName -SchemaSourceObject $Schema `
-AzAppId $AzAppId -AzAppSecret $AzAppSecret -TenantId $TenantId -Verbose:$Verbose
#-----------------------------------------------------------------------------------------------
# Structure check = $true -> Create/update table & DCR with necessary schema
#-----------------------------------------------------------------------------------------------
If ($StructureCheck -eq $true)
{
If ( ( $env:COMPUTERNAME -in $AzLogDcrTableCreateFromReferenceMachine) -or ($AzLogDcrTableCreateFromAnyMachine -eq $true) ) # manage table creations
{
# build schema to be used for LogAnalytics Table
$Schema = Get-ObjectSchemaAsHash -Data $Data -ReturnType Table -Verbose:$Verbose
$ResultLA = CreateUpdate-AzLogAnalyticsCustomLogTableDcr -AzLogWorkspaceResourceId $AzLogWorkspaceResourceId -SchemaSourceObject $Schema -TableName $TableName `
-AzAppId $AzAppId -AzAppSecret $AzAppSecret -TenantId $TenantId -Verbose:$Verbose -SchemaMode $SchemaMode
# build schema to be used for DCR
$Schema = Get-ObjectSchemaAsHash -Data $Data -ReturnType DCR
$ResultDCR = CreateUpdate-AzDataCollectionRuleLogIngestCustomLog -AzLogWorkspaceResourceId $AzLogWorkspaceResourceId -SchemaSourceObject $Schema `
-DceName $DceName -DcrName $DcrName -DcrResourceGroup $DcrResourceGroup -TableName $TableName `
-LogIngestServicePricipleObjectId $LogIngestServicePricipleObjectId -SchemaMode $SchemaMode `
-AzDcrSetLogIngestApiAppPermissionsDcrLevel $AzDcrSetLogIngestApiAppPermissionsDcrLevel `
-AzAppId $AzAppId -AzAppSecret $AzAppSecret -TenantId $TenantId -Verbose:$Verbose
Return $ResultLA, $ResultDCR
}
}
} # create table/DCR
}
}
Function Convert-CimArrayToObjectFixStructure
{
<#
.SYNOPSIS
Converts CIM array and remove CIM class information
.DESCRIPTION
Used to remove "noice" information of columns which we shouldn't send into the logs
.PARAMETER Data
Specifies the data object to modify
.INPUTS
None. You cannot pipe objects
.OUTPUTS
Modified array
.LINK
https://github.com/KnudsenMorten/AzLogDcrIngestPS
.EXAMPLE
#-------------------------------------------------------------------------------------------
# Variables
#-------------------------------------------------------------------------------------------
$Verbose = $true # $true or $false
#-------------------------------------------------------------------------------------------
# Collecting data (in)
#-------------------------------------------------------------------------------------------
$DNSName = (Get-CimInstance win32_computersystem).DNSHostName +"." + (Get-CimInstance win32_computersystem).Domain
$ComputerName = (Get-CimInstance win32_computersystem).DNSHostName
[datetime]$CollectionTime = ( Get-date ([datetime]::Now.ToUniversalTime()) -format "yyyy-MM-ddTHH:mm:ssK" )
$UserLoggedOnRaw = Get-Process -IncludeUserName -Name explorer | Select-Object UserName -Unique
$UserLoggedOn = $UserLoggedOnRaw.UserName
$DataVariable = Get-CimInstance -ClassName Win32_Processor | Select-Object -ExcludeProperty "CIM*"
#-------------------------------------------------------------------------------------------
# Preparing data structure
#-------------------------------------------------------------------------------------------
$DataVariable = Convert-CimArrayToObjectFixStructure -data $DataVariable -Verbose:$Verbose
$DataVariable
#-------------------------------------------------------------------------------------------
# Output
#-------------------------------------------------------------------------------------------