/
ConvertFrom-MDMDiagReportXML.ps1
922 lines (794 loc) · 44.4 KB
/
ConvertFrom-MDMDiagReportXML.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
function ConvertFrom-MDMDiagReportXML {
<#
.SYNOPSIS
Function for converting Intune XML report generated by MdmDiagnosticsTool.exe to a PowerShell object.
.DESCRIPTION
Function for converting Intune XML report generated by MdmDiagnosticsTool.exe to a PowerShell object.
There is also option to generate HTML report instead.
.PARAMETER computerName
(optional) Computer name from which you want to get data from.
.PARAMETER MDMDiagReport
Path to MDMDiagReport.xml.
If not specified, new report will be generated and used.
.PARAMETER asHTML
Switch for outputting results as a HTML page instead of PowerShell object.
PSWriteHtml module is required!
.PARAMETER HTMLReportPath
Path to html file where HTML report should be stored.
Default is '<yourUserProfile>\IntuneReport.html'.
.PARAMETER showEnrollmentIDs
Switch for adding EnrollmentID property i.e. property containing Enrollment ID of given policy.
From my point of view its useless :).
.PARAMETER showURLs
Switch for adding PolicyURL and PolicySettingsURL properties i.e. properties containing URL with Microsoft documentation for given CSP.
Make running the function slower! Because I test each URL and shows just existing ones.
.PARAMETER showConnectionData
Switch for showing Intune connection data.
Beware that this will add new object type to the output (but it doesn't matter if you use asHTML switch).
.EXAMPLE
$intuneReport = ConvertFrom-MDMDiagReportXML
$intuneReport | Out-GridView
Generates new Intune report, converts it into PowerShell object and output it using Out-GridView.
.EXAMPLE
ConvertFrom-MDMDiagReportXML -asHTML -showURLs
Generates new Intune report (policies documentation URL included), converts it into HTML web page and opens it.
.NOTES
Author: Ondrej Sebela (ztrhgf@seznam.cz)
URL: https://doitpsway.com/get-a-better-intune-policy-report-part-2
#>
[CmdletBinding()]
param (
[string] $computerName,
[ValidateScript( {
if ($_ -match "\.xml$") {
$true
} else {
throw "$_ is not a valid path to MDM xml report"
}
})]
[string] $MDMDiagReport,
[switch] $asHTML,
[ValidateScript( {
if ($_ -match "\.html$") {
$true
} else {
throw "$_ is not a valid path to html file. Enter something like 'C:\destination\intune.html'"
}
})]
[string] $HTMLReportPath = (Join-Path $env:USERPROFILE "IntuneReport.html"),
[switch] $showEnrollmentIDs,
[switch] $showURLs,
[switch] $showConnectionData
)
if ($asHTML) {
# array of results that will be in the end transformed into HTML report
$results = @()
if (!(Get-Module 'PSWriteHtml') -and (!(Get-Module 'PSWriteHtml' -ListAvailable))) {
throw "Module PSWriteHtml is missing. To get it use command: Install-Module PSWriteHtml -Scope CurrentUser"
}
# create parent directory if not exists
[Void][System.IO.Directory]::CreateDirectory((Split-Path $HTMLReportPath -Parent))
}
if ($computerName) {
$session = New-PSSession -ComputerName $computerName -ErrorAction Stop
}
if (!$MDMDiagReport) {
++$reportNotSpecified
$MDMDiagReport = "$env:PUBLIC\Documents\MDMDiagnostics\MDMDiagReport.xml"
}
$MDMDiagReportFolder = Split-Path $MDMDiagReport -Parent
# generate XML report if necessary
if ($reportNotSpecified) {
if ($computerName) {
# XML report is on remote computer, transform to UNC path
$MDMDiagReport = "\\$computerName\$($MDMDiagReport -replace ":", "$")"
Write-Verbose "Generating '$MDMDiagReport'..."
try {
Invoke-Command -Session $session {
param ($MDMDiagReportFolder)
Start-Process MdmDiagnosticsTool.exe -Wait -ArgumentList "-out `"$MDMDiagReportFolder`"" -NoNewWindow -ErrorAction Stop
} -ArgumentList $MDMDiagReportFolder -ErrorAction Stop
} catch {
throw "Unable to generate XML report`nError: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)"
}
} else {
Write-Verbose "Generating '$MDMDiagReport'..."
Start-Process MdmDiagnosticsTool.exe -Wait -ArgumentList "-out `"$MDMDiagReportFolder`"" -NoNewWindow
}
}
if (!(Test-Path $MDMDiagReport -PathType Leaf)) {
Write-Verbose "'$MDMDiagReport' doesn't exist, generating..."
Start-Process MdmDiagnosticsTool.exe -Wait -ArgumentList "-out `"$MDMDiagReportFolder`"" -NoNewWindow
}
Write-Verbose "Converting '$MDMDiagReport' to XML object"
[xml]$xml = Get-Content $MDMDiagReport -Raw -ErrorAction Stop
#region get enrollmentID
Write-Verbose "Getting EnrollmentID"
_Write-ProgressHelper -Message "Getting EnrollmentID" -StepNumber ($parentStep++) -totalSteps 8 -id 1
$scriptBlock = {
Get-ScheduledTask -TaskName "*pushlaunch*" -TaskPath "\Microsoft\Windows\EnterpriseMgmt\*" | Select-Object -ExpandProperty TaskPath | Split-Path -Leaf
}
$param = @{
scriptBlock = $scriptBlock
}
if ($computerName) {
$param.session = $session
}
$userEnrollmentID = Invoke-Command @param
Write-Verbose "Your EnrollmentID is $userEnrollmentID"
#endregion get enrollmentID
#region connection data
if ($showConnectionData) {
Write-Verbose "Getting connection data"
$connectionInfo = $xml.MDMEnterpriseDiagnosticsReport.DeviceManagementAccount.Enrollment | ? EnrollmentId -EQ $userEnrollmentID
if ($connectionInfo) {
[PSCustomObject]@{
"EnrollmentId" = $connectionInfo.EnrollmentId
"MDMServerName" = $connectionInfo.ProtectedInformation.MDMServerName
"LastSuccessConnection" = [DateTime]::ParseExact(($connectionInfo.ProtectedInformation.ConnectionInformation.ServerLastSuccessTime -replace "Z$"), 'yyyyMMddTHHmmss', $null)
"LastFailureConnection" = [DateTime]::ParseExact(($connectionInfo.ProtectedInformation.ConnectionInformation.ServerLastFailureTime -replace "Z$"), 'yyyyMMddTHHmmss', $null)
}
} else {
Write-Verbose "Unable to get connection data from $MDMDiagReport"
}
}
#endregion connection data
#region helper functions
function _getTargetName {
param ([string] $id)
Write-Verbose "Translating $id"
if (!$id) {
Write-Verbose "id was null"
return
} elseif ($id -eq 'device') {
# xml nodes contains 'device' instead of 'Device'
return 'Device'
}
$errPref = $ErrorActionPreference
$ErrorActionPreference = "Stop"
try {
if ($id -eq '00000000-0000-0000-0000-000000000000' -or $id -eq 'S-0-0-00-0000000000-0000000000-000000000-000') {
return 'Device'
} elseif ($id -match "^S-1-5-21") {
# it is local account
if ($computerName) {
Invoke-Command -Session $session {
param ($id)
$ErrorActionPreference = "Stop"
try {
return ((New-Object System.Security.Principal.SecurityIdentifier($id)).Translate([System.Security.Principal.NTAccount])).Value
} catch {
throw 1
}
} -ArgumentList $id
} else {
return ((New-Object System.Security.Principal.SecurityIdentifier($id)).Translate([System.Security.Principal.NTAccount])).Value
}
} else {
# it is AzureAD account
if ($getDataFromIntune) {
return (Invoke-MSGraphRequest -Url "https://graph.microsoft.com/beta/users/$id").userPrincipalName
} else {
# unable to translate ID to name because there is no connection to the Intune Graph API
return $id
}
}
} catch {
Write-Verbose "Unable to translate $id account name"
$ErrorActionPreference = $errPref
return $id
}
}
function ConvertFrom-XML {
<#
.SYNOPSIS
Function for converting XML object (XmlNode) to PSObject.
.DESCRIPTION
Function for converting XML object (XmlNode) to PSObject.
.PARAMETER node
XmlNode object (retrieved like: [xml]$xmlObject = (Get-Content C:\temp\file.xml -Raw))
.EXAMPLE
[xml]$xmlObject = (Get-Content C:\temp\file.xml -Raw)
ConvertFrom-XML $xmlObject
.NOTES
Based on https://stackoverflow.com/questions/3242995/convert-xml-to-psobject
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline)]
[System.Xml.XmlNode] $node
)
#region helper functions
function ConvertTo-PsCustomObjectFromHashtable {
param (
[Parameter(
Position = 0,
Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)] [object[]]$hashtable
);
begin { $i = 0; }
process {
foreach ($myHashtable in $hashtable) {
if ($myHashtable.GetType().Name -eq 'hashtable') {
$output = New-Object -TypeName PsObject;
Add-Member -InputObject $output -MemberType ScriptMethod -Name AddNote -Value {
Add-Member -InputObject $this -MemberType NoteProperty -Name $args[0] -Value $args[1];
};
$myHashtable.Keys | Sort-Object | % {
$output.AddNote($_, $myHashtable.$_);
}
$output
} else {
Write-Warning "Index $i is not of type [hashtable]";
}
$i += 1;
}
}
}
#endregion helper functions
$hash = @{}
foreach ($attribute in $node.attributes) {
$hash.$($attribute.name) = $attribute.Value
}
$childNodesList = ($node.childnodes | ? { $_ -ne $null }).LocalName
foreach ($childnode in ($node.childnodes | ? { $_ -ne $null })) {
if (($childNodesList.where( { $_ -eq $childnode.LocalName })).count -gt 1) {
if (!($hash.$($childnode.LocalName))) {
Write-Verbose "ChildNode '$($childnode.LocalName)' isn't in hash. Creating empty array and storing in hash.$($childnode.LocalName)"
$hash.$($childnode.LocalName) += @()
}
if ($childnode.'#text') {
Write-Verbose "Into hash.$($childnode.LocalName) adding '$($childnode.'#text')'"
$hash.$($childnode.LocalName) += $childnode.'#text'
} else {
Write-Verbose "Into hash.$($childnode.LocalName) adding result of ConvertFrom-XML called upon '$($childnode.Name)' node object"
$hash.$($childnode.LocalName) += ConvertFrom-XML($childnode)
}
} else {
Write-Verbose "In ChildNode list ($($childNodesList -join ', ')) is only one node '$($childnode.LocalName)'"
if ($childnode.'#text') {
Write-Verbose "Into hash.$($childnode.LocalName) set '$($childnode.'#text')'"
$hash.$($childnode.LocalName) = $childnode.'#text'
} else {
Write-Verbose "Into hash.$($childnode.LocalName) set result of ConvertFrom-XML called upon '$($childnode.Name)' $($childnode.Value) object"
$hash.$($childnode.LocalName) = ConvertFrom-XML($childnode)
}
}
}
Write-Verbose "Returning hash ($($hash.Values -join ', '))"
return $hash | ConvertTo-PsCustomObjectFromHashtable
}
function Test-URLStatus {
param ($URL)
try {
$response = [System.Net.WebRequest]::Create($URL).GetResponse()
$status = $response.StatusCode
$response.Close()
if ($status -eq 'OK') { return $true } else { return $false }
} catch {
return $false
}
}
function _translateStatus {
param ([int] $statusCode)
$statusMessage = ""
switch ($statusCode) {
'10' { $statusMessage = "Initialized" }
'20' { $statusMessage = "Download In Progress" }
'25' { $statusMessage = "Pending Download Retry" }
'30' { $statusMessage = "Download Failed" }
'40' { $statusMessage = "Download Completed" }
'48' { $statusMessage = "Pending User Session" }
'50' { $statusMessage = "Enforcement In Progress" }
'55' { $statusMessage = "Pending Enforcement Retry" }
'60' { $statusMessage = "Enforcement Failed" }
'70' { $statusMessage = "Enforcement Completed" }
default { $statusMessage = $statusCode }
}
return $statusMessage
}
#endregion helper functions
if ($showURLs) {
$clientIsOnline = Test-URLStatus 'https://google.com'
}
#region enrollments
Write-Verbose "Getting Enrollments (MDMEnterpriseDiagnosticsReport.Resources.Enrollment)"
$enrollment = $xml.MDMEnterpriseDiagnosticsReport.Resources.Enrollment | % { ConvertFrom-XML $_ }
if ($enrollment) {
Write-Verbose "Processing Enrollments"
$enrollment | % {
<#
<Resources>
<Enrollment>
<EnrollmentID>5AFCD0A0-321F-4635-B3EB-2EBD28A0FD9A</EnrollmentID>
<Scope>
<ResourceTarget>device</ResourceTarget>
<Resources>
<Type>default</Type>
<ResourceName>./device/Vendor/MSFT/DeviceManageability/Provider/WMI_Bridge_Server</ResourceName>
<ResourceName>2</ResourceName>
<ResourceName>./device/Vendor/MSFT/VPNv2/K_AlwaysOn_VPN</ResourceName>
</Resources>
</Scope>
#>
$policy = $_
$enrollmentId = $_.EnrollmentId
$policy.Scope | % {
$scope = _getTargetName $_.ResourceTarget
foreach ($policyAreaName in $_.Resources.ResourceName) {
# some policies have just number instead of any name..I don't know what it means so I ignore them
if ($policyAreaName -match "^\d+$") {
continue
}
# get rid of MSI installations (I have them with details in separate section)
if ($policyAreaName -match "/Vendor/MSFT/EnterpriseDesktopAppManagement/MSI") {
continue
}
# get rid of useless data
if ($policyAreaName -match "device/Vendor/MSFT/DeviceManageability/Provider/WMI_Bridge_Server") {
continue
}
Write-Verbose "`nEnrollment '$enrollmentId' applied to '$scope' configures resource '$policyAreaName'"
#region get policy settings details
$settingDetails = $null
#TODO zjistit co presne to nastavuje
# - policymanager.configsource.policyscope.Area
<#
<ErrorLog>
<Component>ConfigManager</Component>
<SubComponent>
<Name>BitLocker</Name>
<Error>-2147024463</Error>
<Metadata1>CmdType_Set</Metadata1>
<Metadata2>./Device/Vendor/MSFT/BitLocker/RequireDeviceEncryption</Metadata2>
<Time>2021-09-23 07:07:05.463</Time>
</SubComponent>
#>
Write-Verbose "Getting Errors (MDMEnterpriseDiagnosticsReport.Diagnostics.ErrorLog)"
# match operator used for metadata2 because for example WIFI networks are saved there as ./Vendor/MSFT/WiFi/Profile/<wifiname> instead of ./Vendor/MSFT/WiFi/Profile
foreach ($errorRecord in $xml.MDMEnterpriseDiagnosticsReport.Diagnostics.ErrorLog) {
$component = $errorRecord.component
$errorRecord.subComponent | % {
$subComponent = $_
if ($subComponent.name -eq $policyAreaName -or $subComponent.Metadata2 -match [regex]::Escape($policyAreaName)) {
$settingDetails = $subComponent | Select-Object @{n = 'Component'; e = { $component } }, @{n = 'SubComponent'; e = { $subComponent.Name } }, @{n = 'SettingName'; e = { $policyAreaName } }, Error, @{n = 'Time'; e = { Get-Date $subComponent.Time } }
break
}
}
}
if (!$settingDetails) {
# try more "relaxed" search
if ($policyAreaName -match "/") {
# it is just common setting, try to find it using last part of the policy name
$policyAreaNameID = ($policyAreaName -split "/")[-1]
Write-Verbose "try to find just ID part ($policyAreaNameID) of the policy name in MDMEnterpriseDiagnosticsReport.Diagnostics.ErrorLog"
# I don't search substring of policy name in Metadata2 because there can be multiple similar policies (./user/Vendor/MSFT/VPNv2/VPN_Backup vs ./device/Vendor/MSFT/VPNv2/VPN_Backup)
foreach ($errorRecord in $xml.MDMEnterpriseDiagnosticsReport.Diagnostics.ErrorLog) {
$component = $errorRecord.component
$errorRecord.subComponent | % {
$subComponent = $_
if ($subComponent.name -eq $policyAreaNameID) {
$settingDetails = $subComponent | Select-Object @{n = 'Component'; e = { $component } }, @{n = 'SubComponent'; e = { $subComponent.Name } }, @{n = 'SettingName'; e = { $policyAreaName } }, Error, @{n = 'Time'; e = { Get-Date $subComponent.Time } }
break
}
}
}
} else {
Write-Verbose "'$policyAreaName' doesn't contains '/'"
}
if (!$settingDetails) {
Write-Verbose "No additional data was found for '$policyAreaName' (it means it was successfully applied)"
}
}
#endregion get policy settings details
# get CSP policy URL if available
if ($showURLs) {
if ($policyAreaName -match "/") {
$pName = ($policyAreaName -split "/")[-2]
} else {
$pName = $policyAreaName
}
$policyURL = "https://docs.microsoft.com/en-us/windows/client-management/mdm/$pName-csp"
# check that URL exists
if ($clientIsOnline) {
if (!(Test-URLStatus $policyURL)) {
# URL doesn't exist
if ($policyAreaName -match "/") {
# sometimes name of the CSP is not second from the end but third
$pName = ($policyAreaName -split "/")[-3]
$policyURL = "https://docs.microsoft.com/en-us/windows/client-management/mdm/$pName-csp"
if (!(Test-URLStatus $policyURL)) {
$policyURL = $null
}
} else {
$policyURL = "https://docs.microsoft.com/en-us/windows/client-management/mdm/policy-csp-$pName"
if (!(Test-URLStatus $policyURL)) {
$policyURL = $null
}
}
}
}
}
#region return retrieved data
$property = [ordered] @{
Scope = $scope
PolicyName = $policyAreaName
SettingName = $policyAreaName
SettingDetails = $settingDetails
}
if ($showEnrollmentIDs) { $property.EnrollmentId = $enrollmentId }
if ($showURLs) { $property.PolicyURL = $policyURL }
$result = New-Object -TypeName PSObject -Property $property
if ($asHTML) {
$results += $result
} else {
$result
}
#endregion return retrieved data
}
}
}
}
#endregion enrollments
#region policies
Write-Verbose "Getting Policies (MDMEnterpriseDiagnosticsReport.PolicyManager.ConfigSource)"
$policyManager = $xml.MDMEnterpriseDiagnosticsReport.PolicyManager.ConfigSource | % { ConvertFrom-XML $_ }
# filter out useless knobs
$policyManager = $policyManager | ? { $_.policyScope.Area.PolicyAreaName -ne 'knobs' }
if ($policyManager) {
Write-Verbose "Processing Policies"
# get policies metadata
Write-Verbose "Getting Policies Area metadata (MDMEnterpriseDiagnosticsReport.PolicyManager.AreaMetadata)"
$policyAreaNameMetadata = $xml.MDMEnterpriseDiagnosticsReport.PolicyManager.AreaMetadata
# get admx policies metadata
# there are duplicities, so pick just last one
Write-Verbose "Getting Policies ADMX metadata (MDMEnterpriseDiagnosticsReport.PolicyManager.IngestedAdmxPolicyMetadata)"
$admxPolicyAreaNameMetadata = $xml.MDMEnterpriseDiagnosticsReport.PolicyManager.IngestedAdmxPolicyMetadata | % { ConvertFrom-XML $_ }
Write-Verbose "Getting Policies winning provider (MDMEnterpriseDiagnosticsReport.PolicyManager.CurrentPolicies.CurrentPolicyValues)"
$winningProviderPolicyAreaNameMetadata = $xml.MDMEnterpriseDiagnosticsReport.PolicyManager.CurrentPolicies.CurrentPolicyValues | % {
$_.psobject.properties | ? { $_.Name -Match "_WinningProvider$" } | Select-Object Name, Value
}
$policyManager | % {
$policy = $_
$enrollmentId = $_.EnrollmentId
$policy.policyScope | % {
$scope = _getTargetName $_.PolicyScope
$_.Area | % {
<#
<ConfigSource>
<EnrollmentId>AB068787-67D2-4F7C-AA87-A9127A87411F</EnrollmentId>
<PolicyScope>
<PolicyScope>Device</PolicyScope>
<Area>
<PolicyAreaName>BitLocker</PolicyAreaName>
<AllowWarningForOtherDiskEncryption>0</AllowWarningForOtherDiskEncryption>
<AllowWarningForOtherDiskEncryption_LastWrite>1</AllowWarningForOtherDiskEncryption_LastWrite>
<RequireDeviceEncryption>1</RequireDeviceEncryption>
#>
$policyAreaName = $_.PolicyAreaName
Write-Verbose "`nEnrollment '$enrollmentId' applied to '$scope' configures area '$policyAreaName'"
$policyAreaSetting = $_ | Select-Object -Property * -ExcludeProperty 'PolicyAreaName', "*_LastWrite"
$policyAreaSettingName = $policyAreaSetting | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty name
if ($policyAreaSettingName.count -eq 1 -and $policyAreaSettingName -eq "*") {
# bug? when there is just PolicyAreaName and none other object than probably because of exclude $policyAreaSettingName instead of be null returns one empty object '*'
$policyAreaSettingName = $null
$policyAreaSetting = $null
}
#region get policy settings details
$settingDetails = @()
if ($policyAreaSetting) {
Write-Verbose "`tIt configures these settings:"
# $policyAreaSetting is object, so I have to iterate through its properties
foreach ($setting in $policyAreaSetting.PSObject.Properties) {
$settingName = $setting.Name
$settingValue = $setting.Value
# PolicyAreaName property was already picked up so now I will ignore it
if ($settingName -eq "PolicyAreaName") { continue }
Write-Verbose "`t`t- $settingName ($settingValue)"
# makes test of url slow
# if ($clientIsOnline) {
# if (!(Test-URLStatus $policyDetailsURL)) {
# # URL doesn't exist
# $policyDetailsURL = $null
# }
# }
if ($showURLs) {
if ($policyAreaName -match "~Policy~OneDriveNGSC") {
# doesn't have policy csp url
$policyDetailsURL = $null
} else {
$policyDetailsURL = "https://docs.microsoft.com/en-us/windows/client-management/mdm/policy-csp-$policyAreaName#$(($policyAreaName).tolower())-$(($settingName).tolower())"
}
}
# define base object
$property = [ordered]@{
"SettingName" = $settingName
"Value" = $settingValue
"DefaultValue" = $null
"PolicyType" = '*unknown*'
"RegKey" = '*unknown*'
"RegValueName" = '*unknown*'
"SourceAdmxFile" = $null
"WinningProvider" = $null
}
if ($showURLs) { $property.PolicyDetailsURL = $policyDetailsURL }
$additionalData = $policyAreaNameMetadata | ? PolicyAreaName -EQ $policyAreaName | Select-Object -ExpandProperty PolicyMetadata | ? PolicyName -EQ $settingName | Select-Object PolicyType, Value, RegKeyPathRedirect, RegValueNameRedirect
if ($additionalData) {
Write-Verbose "Additional data for '$settingName' was found in policyAreaNameMetadata"
<#
<PolicyMetadata>
<PolicyName>RecoveryEnvironmentAuthentication</PolicyName>
<Behavior>49</Behavior>
<highrange>2</highrange>
<lowrange>0</lowrange>
<mergealgorithm>3</mergealgorithm>
<policytype>4</policytype>
<RegKeyPathRedirect>Software\Policies\Microsoft\WinRE</RegKeyPathRedirect>
<RegValueNameRedirect>WinREAuthenticationRequirement</RegValueNameRedirect>
<value>0</value>
</PolicyMetadata>
#>
$property.DefaultValue = $additionalData.Value
$property.PolicyType = $additionalData.PolicyType
$property.RegKey = $additionalData.RegKeyPathRedirect
$property.RegValueName = $additionalData.RegValueNameRedirect
} else {
# no additional data was found in policyAreaNameMetadata
# trying to get them from admxPolicyAreaNameMetadata
<#
<IngestedADMXPolicyMetaData>
<EnrollmentId>11120759-7CE3-4683-AB59-46C27FF40D35</EnrollmentId>
<AreaName>
<ADMXIngestedAreaName>OneDriveNGSCv2~Policy~OneDriveNGSC</ADMXIngestedAreaName>
<PolicyMetadata>
<PolicyName>BlockExternalSync</PolicyName>
<SourceAdmxFile>OneDriveNGSCv2</SourceAdmxFile>
<Behavior>224</Behavior>
<MergeAlgorithm>3</MergeAlgorithm>
<RegKeyPathRedirect>SOFTWARE\Policies\Microsoft\OneDrive</RegKeyPathRedirect>
<RegValueNameRedirect>BlockExternalSync</RegValueNameRedirect>
<PolicyType>1</PolicyType>
<AdmxMetadataDevice>30313D0100000000323D000000000000</AdmxMetadataDevice>
</PolicyMetadata>
#>
$additionalData = ($admxPolicyAreaNameMetadata.AreaName | ? { $_.ADMXIngestedAreaName -eq $policyAreaName }).PolicyMetadata | ? { $_.PolicyName -EQ $settingName } | select -First 1 # sometimes there are duplicities in results
if ($additionalData) {
Write-Verbose "Additional data for '$settingName' was found in admxPolicyAreaNameMetadata"
$property.PolicyType = $additionalData.PolicyType
$property.RegKey = $additionalData.RegKeyPathRedirect
$property.RegValueName = $additionalData.RegValueNameRedirect
$property.SourceAdmxFile = $additionalData.SourceAdmxFile
} else {
Write-Verbose "No additional data found for $settingName"
}
}
$winningProvider = $winningProviderPolicyAreaNameMetadata | ? Name -EQ "$settingName`_WinningProvider" | Select-Object -ExpandProperty Value
if ($winningProvider) {
if ($winningProvider -eq $userEnrollmentID) {
$winningProvider = 'Intune'
}
$property.WinningProvider = $winningProvider
}
$settingDetails += New-Object -TypeName PSObject -Property $property
}
} else {
Write-Verbose "`tIt doesn't contain any settings"
}
#endregion get policy settings details
# get CSP policy URL if available
if ($showURLs) {
if ($policyAreaName -match "/") {
$pName = ($policyAreaName -split "/")[-2]
} else {
$pName = $policyAreaName
}
$policyURL = "https://docs.microsoft.com/en-us/windows/client-management/mdm/$pName-csp"
# check that URL exists
if ($clientIsOnline) {
if (!(Test-URLStatus $policyURL)) {
# URL doesn't exist
if ($policyAreaName -match "/") {
# sometimes name of the CSP is not second from the end but third
$pName = ($policyAreaName -split "/")[-3]
$policyURL = "https://docs.microsoft.com/en-us/windows/client-management/mdm/$pName-csp"
if (!(Test-URLStatus $policyURL)) {
$policyURL = $null
}
} else {
$policyURL = "https://docs.microsoft.com/en-us/windows/client-management/mdm/policy-csp-$pName"
if (!(Test-URLStatus $policyURL)) {
$policyURL = $null
}
}
}
}
}
#region return retrieved data
$property = [ordered] @{
Scope = $scope
PolicyName = $policyAreaName
SettingName = $policyAreaSettingName
SettingDetails = $settingDetails
}
if ($showEnrollmentIDs) { $property.EnrollmentId = $enrollmentId }
if ($showURLs) { $property.PolicyURL = $policyURL }
$result = New-Object -TypeName PSObject -Property $property
if ($asHTML) {
$results += $result
} else {
$result
}
#endregion return retrieved data
}
}
}
}
#endregion policies
#region installations
Write-Verbose "Getting MSI installations (MDMEnterpriseDiagnosticsReport.EnterpriseDesktopAppManagementinfo.MsiInstallations)"
$installation = $xml.MDMEnterpriseDiagnosticsReport.EnterpriseDesktopAppManagementinfo.MsiInstallations | % { ConvertFrom-XML $_ }
if ($installation) {
Write-Verbose "Processing MSI installations"
$settingDetails = @()
$installation.TargetedUser | % {
<#
<MsiInstallations>
<TargetedUser>
<UserSid>S-0-0-00-0000000000-0000000000-000000000-000</UserSid>
<Package>
<Type>MSI</Type>
<Details>
<PackageId>{23170F69-40C1-2702-1900-000001000000}</PackageId>
<DownloadInstall>Ready</DownloadInstall>
<ProductCode>{23170F69-40C1-2702-1900-000001000000}</ProductCode>
<ProductVersion>19.00.00.0</ProductVersion>
<ActionType>1</ActionType>
<Status>70</Status>
<JobStatusReport>1</JobStatusReport>
<LastError>0</LastError>
<BITSJobId></BITSJobId>
<DownloadLocation></DownloadLocation>
<CurrentDownloadUrlIndex>0</CurrentDownloadUrlIndex>
<CurrentDownloadUrl></CurrentDownloadUrl>
<FileHash>A7803233EEDB6A4B59B3024CCF9292A6FFFB94507DC998AA67C5B745D197A5DC</FileHash>
<CommandLine>ALLUSERS=1</CommandLine>
<AssignmentType>1</AssignmentType>
<EnforcementTimeout>30</EnforcementTimeout>
<EnforcementRetryIndex>0</EnforcementRetryIndex>
<EnforcementRetryCount>5</EnforcementRetryCount>
<EnforcementRetryInterval>3</EnforcementRetryInterval>
<LocURI>./Device/Vendor/MSFT/EnterpriseDesktopAppManagement/MSI/{23170F69-40C1-2702-1900-000001000000}/DownloadInstall</LocURI>
<ServerAccountID>11120759-7CE3-4683-FB59-46C27FF40D35</ServerAccountID>
</Details>
#>
$userSID = $_.UserSid
$type = $_.Package.Type
$details = $_.Package.details
$details | % {
Write-Verbose "`t$($_.PackageId) of type $type"
# define base object
$property = [ordered]@{
"Scope" = _getTargetName $userSID
"Type" = $type
"Status" = _translateStatus $_.Status
"LastError" = $_.LastError
"ProductVersion" = $_.ProductVersion
"CommandLine" = $_.CommandLine
"RetryIndex" = $_.EnforcementRetryIndex
"MaxRetryCount" = $_.EnforcementRetryCount
"PackageId" = $_.PackageId -replace "{" -replace "}"
}
$settingDetails += New-Object -TypeName PSObject -Property $property
}
}
#region return retrieved data
$property = [ordered] @{
Scope = $null
PolicyName = "SoftwareInstallation" # made up!
SettingName = $null
SettingDetails = $settingDetails
}
if ($showEnrollmentIDs) { $property.EnrollmentId = $null }
if ($showURLs) { $property.PolicyURL = $null } # this property only to have same properties for all returned objects
$result = New-Object -TypeName PSObject -Property $property
if ($asHTML) {
$results += $result
} else {
$result
}
#endregion return retrieved data
}
#endregion installations
#region convert results to HTML and output
if ($asHTML -and $results) {
Write-Verbose "Converting to HTML"
# split the results
$resultsWithSettings = @()
$resultsWithoutSettings = @()
$results | % {
if ($_.settingDetails) {
$resultsWithSettings += $_
} else {
$resultsWithoutSettings += $_
}
}
New-HTML -TitleText "Intune Report" -Online -FilePath $HTMLReportPath -ShowHTML {
# it looks better to have headers and content in center
New-HTMLTableStyle -TextAlign center
New-HTMLSection -HeaderText 'Intune Report' -Direction row -HeaderBackGroundColor Black -HeaderTextColor White -HeaderTextSize 20 {
if ($resultsWithoutSettings) {
New-HTMLSection -HeaderText "Policies without settings details" -HeaderTextAlignment left -CanCollapse -BackgroundColor DeepSkyBlue -HeaderBackGroundColor DeepSkyBlue -HeaderTextSize 10 -HeaderTextColor EgyptianBlue -Direction row {
#region prepare data
# exclude some not significant or needed properties
# SettingName is empty (or same as PolicyName)
# settingDetails is empty
$excludeProperty = @('SettingName', 'SettingDetails')
if (!$showEnrollmentIDs) { $excludeProperty += 'EnrollmentId' }
if (!$showURLs) { $excludeProperty += 'PolicyURL' }
$resultsWithoutSettings = $resultsWithoutSettings | Select-Object -Property * -exclude $excludeProperty
# sort
$resultsWithoutSettings = $resultsWithoutSettings | Sort-Object -Property Scope, PolicyName
#endregion prepare data
# render policies
New-HTMLSection -HeaderText 'Policy' -HeaderBackGroundColor Wedgewood -BackgroundColor White {
New-HTMLTable -DataTable $resultsWithoutSettings -WordBreak 'break-all' -DisableInfo -HideButtons -DisablePaging -FixedHeader -FixedFooter
}
}
}
if ($resultsWithSettings) {
New-HTMLSection -HeaderText "Policies with settings details" -HeaderTextAlignment left -CanCollapse -BackgroundColor DeepSkyBlue -HeaderBackGroundColor DeepSkyBlue -HeaderTextSize 10 -HeaderTextColor EgyptianBlue -Direction row {
# sort
$resultsWithSettings = $resultsWithSettings | Sort-Object -Property Scope, PolicyName
$resultsWithSettings | % {
$policy = $_
$policySetting = $_.settingDetails
#region prepare data
# exclude some not significant or needed properties
# SettingName is useless in HTML report from my point of view
# settingDetails will be shown in separate table, omit here
if ($showEnrollmentIDs) {
$excludeProperty = 'SettingName', 'SettingDetails'
} else {
$excludeProperty = 'SettingName', 'SettingDetails', 'EnrollmentId'
}
$policy = $policy | Select-Object -Property * -ExcludeProperty $excludeProperty
#endregion prepare data
New-HTMLSection -HeaderText $policy.PolicyName -HeaderTextAlignment left -CanCollapse -BackgroundColor White -HeaderBackGroundColor White -HeaderTextSize 12 -HeaderTextColor EgyptianBlue {
# render main policy
New-HTMLSection -HeaderText 'Policy' -HeaderBackGroundColor Wedgewood -BackgroundColor White {
New-HTMLTable -DataTable $policy -WordBreak 'break-all' -HideFooter -DisableInfo -HideButtons -DisablePaging -DisableSearch -DisableOrdering
}
# render policy settings details
if ($policySetting) {
if (@($policySetting).count -eq 1) {
$detailsHTMLTableParam = @{
DisableSearch = $true
DisableOrdering = $true
}
} else {
$detailsHTMLTableParam = @{}
}
New-HTMLSection -HeaderText 'Policy settings' -HeaderBackGroundColor PictonBlue -BackgroundColor White {
New-HTMLTable @detailsHTMLTableParam -DataTable $policySetting -WordBreak 'break-all' -AllProperties -FixedHeader -HideFooter -DisableInfo -HideButtons -DisablePaging -WarningAction SilentlyContinue {
New-HTMLTableCondition -Name 'WinningProvider' -ComparisonType string -Operator 'ne' -Value 'Intune' -BackgroundColor Red -Color White #-Row
New-HTMLTableCondition -Name 'LastError' -ComparisonType number -Operator 'ne' -Value 0 -BackgroundColor Red -Color White # -Row
New-HTMLTableCondition -Name 'Error' -ComparisonType number -Operator 'ne' -Value 0 -BackgroundColor Red -Color White # -Row
}
}
}
}
# hack for getting new line between sections
New-HTMLText -Text '.' -Color DeepSkyBlue
}
}
}
} # end of main HTML section
}
}
#endregion convert results to HTML and output
if ($computerName) {
Remove-PSSession $session
}
}