Repository navigation
Expand file tree
/
Copy pathConfigMgrClientHealth.ps1
More file actions
4484 lines (3933 loc) · 215 KB
/
Copy pathConfigMgrClientHealth.ps1
File metadata and controls
4484 lines (3933 loc) · 215 KB
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
ConfigMgr Client Health is a tool that validates and automatically fixes errors on Windows computers managed by Microsoft Configuration Manager.
.EXAMPLE
.\ConfigMgrClientHealth.ps1 -Config .\config.json
.EXAMPLE
.\ConfigMgrClientHealth.ps1 -Config .\config.json -Webservice http://sccm01:5000
.PARAMETER Config
Path to the configuration file (.json or .xml).
.PARAMETER Webservice
A single parameter specifying the URI to the ConfigMgr Client Health Webservice.
.DESCRIPTION
ConfigMgr Client Health detects and fixes following errors:
* ConfigMgr client is not installed.
* ConfigMgr client is assigned the correct site code.
* ConfigMgr client is upgraded to current version if not at specified minimum version.
* ConfigMgr client not able to forward state messages to management point.
* ConfigMgr client stuck in provisioning mode.
* ConfigMgr client maximum log file size.
* ConfigMgr client cache size.
* Corrupt WMI.
* Services for ConfigMgr client is not running or disabled.
* Other services can be specified to start and run and specific state.
* Hardware inventory is running at correct schedule
* Group Policy failes to update registry.pol
* Pending reboot blocking updates from installing
* ConfigMgr Client Update Handler is working correctly with registry.pol
* Windows Update Agent not working correctly, causing client not to receive patches.
* Windows Update Agent missing patches that fixes known bugs.
.NOTES
You should run this with at least local administrator rights. It is recommended to run this script under the SYSTEM context.
DO NOT GIVE USERS WRITE ACCESS TO THIS FILE. LOCK IT DOWN !
Author: Anders Rødland
Blog: https://www.andersrodland.com
Twitter: @AndersRodland
.LINK
Full documentation: https://www.andersrodland.com/configmgr-client-health/
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")]
param(
[Parameter(HelpMessage='Path to JSON or XML configuration file')]
[ValidatePattern('\.(xml|json)$')]
[string]$Config,
[Parameter(HelpMessage='URI to ConfigMgr Client Health Webservice')]
[string]$Webservice
)
Begin {
# ConfigMgr Client Health Version
$Version = '0.8.4'
$script:JsonConfig = $null
$script:ConfigRawToCache = $null
$script:ClientReinstalledThisRun = $false
$script:FailureCount = 0
$script:MonitorOnly = $false
$script:WsusDomainPolicyOverride = $false
$script:VCRuntimeCacheBroken = @()
$script:ClientCacheReinstall = $false
$global:ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
#If no config file was passed in, use the default.
If (!$PSBoundParameters.ContainsKey('Config')) {
# Prefer config.json if it exists, otherwise fall back to Config.xml
$jsonDefault = Join-Path ($global:ScriptPath) "config.json"
$xmlDefault = Join-Path ($global:ScriptPath) "Config.xml"
if (Test-Path $jsonDefault) {
$Config = $jsonDefault
} else {
$Config = $xmlDefault
}
Write-Verbose "No config provided, defaulting to $Config"
}
Write-Verbose "Script version: $Version"
Write-Verbose "PowerShell version: $($PSVersionTable.PSVersion)"
# Retry helper for transient failures (SQL connections, service starts)
Function Invoke-WithRetry {
Param(
[Parameter(Mandatory=$true)][scriptblock]$ScriptBlock,
[int]$MaxRetries = 3,
[int]$DelaySeconds = 5,
[string]$OperationName = 'Operation'
)
for ($i = 1; $i -le $MaxRetries; $i++) {
try { return (& $ScriptBlock) }
catch {
if ($i -eq $MaxRetries) { throw }
Write-Warning "$OperationName failed (attempt $i/$MaxRetries): $_. Retrying in ${DelaySeconds}s..."
Start-Sleep -Seconds $DelaySeconds
}
}
}
# A directory is trusted only when it is a real directory owned by SYSTEM or Administrators,
# with a protected DACL that grants access to SYSTEM and Administrators only.
# Standard users can create folders under ProgramData, so an existing folder proves nothing.
Function Test-TrustedDirectory {
Param([Parameter(Mandatory=$true)][string]$Path)
$trustedSids = @('S-1-5-18', 'S-1-5-32-544')
if (-not (Test-Path -LiteralPath $Path -PathType Container)) { return $false }
try {
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { return $false }
$acl = Get-Acl -LiteralPath $Path -ErrorAction Stop
$owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value
if ($trustedSids -notcontains $owner) { return $false }
if (-not $acl.AreAccessRulesProtected) { return $false }
foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
if ($rule.AccessControlType -ne 'Allow') { continue }
if ($trustedSids -notcontains $rule.IdentityReference.Value) { return $false }
}
return $true
}
catch { return $false }
}
# Deletes without following reparse points. Remove-Item -Recurse on Windows PowerShell 5.1
# can descend into a junction and delete the target's contents.
Function Remove-PathNoFollow {
Param([Parameter(Mandatory=$true)][string]$Path)
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
$isReparsePoint = [bool]($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)
if ($item.PSIsContainer) {
if (-not $isReparsePoint) {
foreach ($child in [System.IO.Directory]::GetFileSystemEntries($Path)) { Remove-PathNoFollow -Path $child }
}
[System.IO.Directory]::Delete($Path, $false)
}
else {
[System.IO.File]::SetAttributes($Path, [System.IO.FileAttributes]::Normal)
[System.IO.File]::Delete($Path)
}
}
# A folder owned by SYSTEM or Administrators is secured in place: it can hold the staged script
# that the CI remediation runs, so it must not move. Items inside it that another account owns,
# and reparse points, are deleted. A folder owned by another account is renamed and recreated.
Function Initialize-SecureDirectory {
Param([Parameter(Mandatory=$true)][string]$Path)
$trustedSids = @('S-1-5-18', 'S-1-5-32-544')
try {
if (-not (Test-TrustedDirectory -Path $Path)) {
if (Test-Path -LiteralPath $Path) {
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
$owner = (Get-Acl -LiteralPath $Path -ErrorAction Stop).GetOwner([System.Security.Principal.SecurityIdentifier]).Value
if (($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -or ($trustedSids -notcontains $owner)) {
$quarantine = "$Path.untrusted-$([guid]::NewGuid().ToString('N'))"
[System.IO.Directory]::Move($Path, $quarantine)
Write-Warning "Untrusted folder '$Path' was renamed to '$quarantine'."
}
}
if (-not (Test-Path -LiteralPath $Path)) { New-Item -Path $Path -ItemType Directory -Force -ErrorAction Stop | Out-Null }
$acl = New-Object System.Security.AccessControl.DirectorySecurity
$acl.SetAccessRuleProtection($true, $false)
foreach ($sid in $trustedSids) {
$identity = New-Object System.Security.Principal.SecurityIdentifier($sid)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
$acl.AddAccessRule($rule)
}
Set-Acl -LiteralPath $Path -AclObject $acl -ErrorAction Stop
# An administrator whose default owner policy is "object creator" owns a new folder personally.
$currentOwner = (Get-Acl -LiteralPath $Path -ErrorAction Stop).GetOwner([System.Security.Principal.SecurityIdentifier]).Value
if ($trustedSids -notcontains $currentOwner) {
$ownerAcl = Get-Acl -LiteralPath $Path -ErrorAction Stop
$ownerAcl.SetOwner((New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')))
Set-Acl -LiteralPath $Path -AclObject $ownerAcl -ErrorAction Stop
}
}
# A trusted folder can still hold an item that another account owns. Copy-Item -Force keeps the
# owner and ACL of a file it overwrites, so a redeploy alone does not restore trust.
$pending =New-Object System.Collections.Generic.Queue[string]
$pending.Enqueue($Path)
while ($pending.Count -gt 0) {
foreach ($entry in [System.IO.Directory]::GetFileSystemEntries($pending.Dequeue())) {
$child = Get-Item -LiteralPath $entry -Force -ErrorAction Stop
$childOwner = (Get-Acl -LiteralPath $entry -ErrorAction Stop).GetOwner([System.Security.Principal.SecurityIdentifier]).Value
if (($child.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -or ($trustedSids -notcontains $childOwner)) {
Write-Warning "Removing untrusted item '$entry'."
Remove-PathNoFollow -Path $entry
}
elseif ($child.PSIsContainer) { $pending.Enqueue($entry) }
}
}
}
catch {
Write-Warning "Could not secure folder '$Path': $($_.Exception.Message)"
return $false
}
return (Test-TrustedDirectory -Path $Path)
}
Function Read-CachedJsonConfig {
Param([Parameter(Mandatory=$true)][string]$CachePath)
if (-not (Test-Path -LiteralPath $CachePath -PathType Leaf)) { return $null }
if (-not (Test-TrustedDirectory -Path (Split-Path $CachePath -Parent))) {
Write-Warning "Cached config at '$CachePath' is in an untrusted folder and is ignored."
return $null
}
try { return (Get-Content -LiteralPath $CachePath -Raw -ErrorAction Stop | ConvertFrom-Json) }
catch { return $null }
}
Function Save-ConfigCache {
Param(
[Parameter(Mandatory=$true)][string]$CachePath,
[Parameter(Mandatory=$true)][string]$Content
)
$cacheDir = Split-Path $CachePath -Parent
if (-not (Initialize-SecureDirectory -Path $cacheDir)) { return }
try {
$tempPath = "$CachePath.tmp"
Set-Content -LiteralPath $tempPath -Value $Content -Encoding UTF8 -Force -ErrorAction Stop
Move-Item -LiteralPath $tempPath -Destination $CachePath -Force -ErrorAction Stop
Write-Verbose "Config cached to $CachePath"
}
catch { Write-Verbose "Could not cache config: $_" }
}
Function Test-XML {
<#
.SYNOPSIS
Test the validity of an XML file
#>
[CmdletBinding()]
param ([parameter(mandatory=$true)][ValidateNotNullorEmpty()][string]$xmlFilePath)
# Check the file exists
if (!(Test-Path -Path $xmlFilePath)) { throw "$xmlFilePath is not valid. Please provide a valid path to the .xml config file" }
# Check for Load or Parse errors when loading the XML file
$xml = New-Object System.Xml.XmlDocument
try {
$xml.Load((Get-ChildItem -Path $xmlFilePath).FullName)
return $true
}
catch [System.Xml.XmlException] {
Write-Error "$xmlFilePath : $($_.toString())"
Write-Error "Configuration file $Config is NOT valid XML. Script will not execute."
return $false
}
}
# Read configuration from file (JSON or XML)
$ConfigCachePath = Join-Path $env:ProgramData 'ConfigMgrClientHealth\config.json.cache'
if ($config) {
if (Test-Path $Config) {
if ($Config -match '\.json$') {
# Load JSON config. The cache is written only after Test-ConfigValues passes.
Try {
$configRaw = Get-Content -Path $Config -Raw -ErrorAction Stop
$script:JsonConfig = $configRaw | ConvertFrom-Json -ErrorAction Stop
$script:ConfigRawToCache = $configRaw
Write-Verbose "JSON configuration loaded from $Config"
}
Catch {
$ErrorMessage = $_.Exception.Message
$script:JsonConfig = Read-CachedJsonConfig -CachePath $ConfigCachePath
if ($script:JsonConfig) {
Write-Warning "Could not read '$Config' ($ErrorMessage). Using cached config from $ConfigCachePath"
}
else {
$text = "Error, could not read $Config. Check file location and share/ntfs permissions. Is JSON config file damaged?"
$text += "`nError message: $ErrorMessage"
Write-Error $text
Exit 1
}
}
}
else {
# Test if valid XML
if ((Test-XML -xmlFilePath $Config) -ne $true ) { Exit 1 }
# Load XML file into variable
Try { $Xml = [xml](Get-Content -Path $Config) }
Catch {
$ErrorMessage = $_.Exception.Message
$text = "Error, could not read $Config. Check file location and share/ntfs permissions. Is XML config file damaged?"
$text += "`nError message: $ErrorMessage"
Write-Error $text
Exit 1
}
}
}
elseif (($Config -match '\.json$') -and (Test-Path $ConfigCachePath)) {
# Network config unreachable - fall back to cached copy
$script:JsonConfig = Read-CachedJsonConfig -CachePath $ConfigCachePath
if ($script:JsonConfig) {
Write-Warning "Config file '$Config' not accessible. Using cached config from $ConfigCachePath"
}
else {
Write-Error "Config file '$Config' not accessible and cached config is missing, corrupt, or untrusted."
Exit 1
}
}
else {
$text = "Error, could not access $Config. Check file location and share/ntfs permissions. Did you misspell the name?"
Write-Error $text
Exit 1
}
}
# Import Modules
# Import BitsTransfer Module (Does not work on PowerShell Core (6), disable check if module failes to import.)
$BitsCheckEnabled = $false
if (Get-Module -ListAvailable -Name BitsTransfer) {
try {
Import-Module BitsTransfer -ErrorAction stop
$BitsCheckEnabled = $true
}
catch { $BitsCheckEnabled = $false }
}
#region functions
Function Get-DateTime {
$format = ([string](Get-XMLConfigLoggingTimeFormat)).ToLower()
# UTC Time
if ($format -like "utc") { $obj = ([DateTime]::UtcNow).ToString("yyyy-MM-dd HH:mm:ss") }
# ClientLocal
else { $obj = (Get-Date -Format "yyyy-MM-dd HH:mm:ss") }
Write-Output $obj
}
# Converts a DateTime object to UTC time.
Function Get-UTCTime {
param([Parameter(Mandatory=$true)][DateTime]$DateTime)
$obj = $DateTime.ToUniversalTime()
Write-Output $obj
}
Function Get-Hostname {
<#
if ($PowerShellVersion -ge 6) { $Obj = (Get-CimInstance Win32_ComputerSystem).Name }
else { $Obj = (Get-WmiObject Win32_ComputerSystem).Name }
#>
$obj = $env:COMPUTERNAME
Write-Output $Obj
}
# Update-WebService use ClientHealth Webservice to update database. RESTful API.
# Windows PowerShell 5.1 on older .NET defaults can omit TLS 1.2.
Function Enable-Tls12 {
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
}
catch { Write-Verbose "Could not enable TLS 1.2: $_" }
}
Function Update-Webservice {
Param([Parameter(Mandatory=$true)][String]$URI, $Log)
Test-ValuesBeforeLogUpdate
# Invoke-RestMethod on Windows PowerShell 5.1 encodes a string body as ISO-8859-1; the API reads UTF-8.
$Body = [System.Text.Encoding]::UTF8.GetBytes(($Log | ConvertTo-Json))
$ApiUri = "$($URI.TrimEnd('/'))/api/Clients"
$ContentType = "application/json; charset=utf-8"
Enable-Tls12
# POST with UPSERT - the API handles create-or-update
try {
Invoke-WithRetry -OperationName 'Webservice POST' -ScriptBlock {
Invoke-RestMethod -Method POST -Uri $ApiUri -Body $Body -ContentType $ContentType -UseDefaultCredentials -UseBasicParsing | Out-Null
}
Write-Verbose "Webservice updated successfully"
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Warning "Error updating webservice at $ApiUri : $ExceptionMessage"
$script:FailureCount++
Out-LogFile -Xml $Xml -Text "ERROR Webservice POST: $ExceptionMessage" -Severity 3
if ($LocalLogging -like 'true') { Out-LogFile -Xml $Xml -Text "ERROR Webservice POST: $ExceptionMessage" -Mode 'Local' -Severity 3 }
}
}
Function Get-LogFileName {
#$OS = Get-WmiObject -class Win32_OperatingSystem
#$OSName = Get-OperatingSystem
$logshare = Get-XMLConfigLoggingShare
#$obj = "$logshare\$OSName\$env:computername.log"
$obj = "$logshare\$env:computername.log"
Write-Output $obj
}
Function Get-ServiceUpTime {
param([Parameter(Mandatory=$true)]$Name)
Try{$ServiceDisplayName = (Get-Service $Name).DisplayName}
Catch{
Write-Warning "The '$($Name)' service could not be found."
Return
}
#First try and get the service start time based on the last start event message in the system log.
Try{
[datetime]$ServiceStartTime = (Get-EventLog -LogName System -Source "Service Control Manager" -EntryType Information -Message "*$($ServiceDisplayName)*running*" -Newest 1).TimeGenerated
Return (New-TimeSpan -Start $ServiceStartTime -End (Get-Date)).Days
}
Catch {
Write-Verbose "Could not get the uptime time for the '$($Name)' service from the event log. Relying on the process instead."
}
#If the event log doesn't contain a start event then use the start time of the service's process. Since processes can be shared this is less reliable.
Try{
$ServiceProcessID = (Get-CimInstance -ClassName Win32_Service -Filter "Name='$($Name)'").ProcessID
[datetime]$ServiceStartTime = (Get-Process -Id $ServiceProcessID).StartTime
Return (New-TimeSpan -Start $ServiceStartTime -End (Get-Date)).Days
}
Catch{
Write-Warning "Could not get the uptime time for the '$($Name)' service. Returning max value."
Return [int]::MaxValue
}
}
#Loop backwards through a Configuration Manager log file looking for the latest matching message after the start time.
Function Search-CMLogFile {
Param(
[Parameter(Mandatory=$true)]$LogFile,
[Parameter(Mandatory=$true)][String[]]$SearchStrings,
[datetime]$StartTime = [datetime]::MinValue
)
#Get the log data.
$LogData = Get-Content $LogFile
#Loop backwards through the log file.
:loop for ($i=($LogData.Count - 1);$i -ge 0; $i--) {
#Parse the log line into its parts.
try{
$LogData[$i] -match '\<\!\[LOG\[(?<Message>.*)?\]LOG\]\!\>\<time=\"(?<Time>.+)(?<TZAdjust>[+|-])(?<TZOffset>\d{2,3})\"\s+date=\"(?<Date>.+)?\"\s+component=\"(?<Component>.+)?\"\s+context="(?<Context>.*)?\"\s+type=\"(?<Type>\d)?\"\s+thread=\"(?<TID>\d+)?\"\s+file=\"(?<Reference>.+)?\"\>' | Out-Null
$LogTime = [datetime]::ParseExact($("$($matches.date) $($matches.time)"),"MM-dd-yyyy HH:mm:ss.fff", $null)
$LogMessage = $matches.message
}
catch{
Write-Warning "Could not parse the line $($i) in '$($LogFile)': $($LogData[$i])"
continue
}
#If we have gone beyond the start time then stop searching.
If ($LogTime -lt $StartTime) {
Write-Verbose "No log lines in $($LogFile) matched $($SearchStrings) before $($StartTime)."
break loop
}
#Loop through each search string looking for a match.
ForEach($String in $SearchStrings){
If ($LogMessage -match $String) {
Write-Output $LogData[$i]
break loop
}
}
}
#Looped through log file without finding a match.
#Return
}
Function Test-LocalLogging {
$clientpath = Get-LocalFilesPath
$stateDir = Join-Path $env:ProgramData 'ConfigMgrClientHealth'
if ($clientpath.TrimEnd('\') -eq $stateDir.TrimEnd('\')) { Initialize-SecureDirectory -Path $stateDir | Out-Null }
elseif ((Test-Path -Path $clientpath) -eq $False) { New-Item -Path $clientpath -ItemType Directory -Force | Out-Null }
}
Function Out-LogFile {
Param([Parameter(Mandatory = $false)][xml]$Xml, $Text, $Mode,
[Parameter(Mandatory = $false)][ValidateSet(1, 2, 3, 'Information', 'Warning', 'Error')]$Severity = 1)
switch ($Severity) {
'Information' {$Severity = 1}
'Warning' {$Severity = 2}
'Error' {$Severity = 3}
}
if ($Mode -like "Local") {
Test-LocalLogging
$clientpath = Get-LocalFilesPath
$Logfile = "$clientpath\ClientHealth.log"
}
else {
# With no share configured the path would be '\<host>.log', the root of the current drive.
if ([string]::IsNullOrWhiteSpace((Get-XMLConfigLoggingShare))) { return }
$Logfile = Get-LogFileName
}
if ($mode -like "ClientInstall" ) {
$text = "ConfigMgr Client installation failed. Agent not detected 10 minutes after triggering installation."
$Severity = 3
}
foreach ($item in $text) {
$item = '<![LOG[' + $item + ']LOG]!>'
$time = 'time="' + (Get-Date -Format HH:mm:ss.fff) + '+000"' #Should actually be the bias
$date = 'date="' + (Get-Date -Format MM-dd-yyyy) + '"'
$component = 'component="ConfigMgrClientHealth"'
$context = 'context=""'
$type = 'type="' + $Severity + '"' #Severity 1=Information, 2=Warning, 3=Error
$thread = 'thread="' + $PID + '"'
$file = 'file=""'
$logblock = ($time, $date, $component, $context, $type, $thread, $file) -join ' '
$logblock = '<' + $logblock + '>'
$item + $logblock | Out-File -Encoding utf8 -Append $logFile
}
# $obj | Out-File -Encoding utf8 -Append $logFile
}
Function Get-OperatingSystem {
$OS = Get-CimInstance -ClassName Win32_OperatingSystem
# Handles different OS languages
$OSArchitecture = ($OS.OSArchitecture -replace ('([^0-9])(\.*)', '')) + '-Bit'
switch -Wildcard ($OS.Caption) {
"*Embedded*" {$OSName = "Windows 7 " + $OSArchitecture}
"*Windows 7*" {$OSName = "Windows 7 " + $OSArchitecture}
"*Windows 8.1*" {$OSName = "Windows 8.1 " + $OSArchitecture}
"*Windows 10*" {$OSName = "Windows 10 " + $OSArchitecture}
"*Windows 11*" {$OSName = "Windows 11 " + $OSArchitecture}
"*Server 2008*" {
if ($OS.Caption -like "*R2*") { $OSName = "Windows Server 2008 R2 " + $OSArchitecture }
else { $OSName = "Windows Server 2008 " + $OSArchitecture }
}
"*Server 2012*" {
if ($OS.Caption -like "*R2*") { $OSName = "Windows Server 2012 R2 " + $OSArchitecture }
else { $OSName = "Windows Server 2012 " + $OSArchitecture }
}
"*Server 2016*" { $OSName = "Windows Server 2016 " + $OSArchitecture }
"*Server 2019*" { $OSName = "Windows Server 2019 " + $OSArchitecture }
"*Server 2022*" { $OSName = "Windows Server 2022 " + $OSArchitecture }
"*Server 2025*" { $OSName = "Windows Server 2025 " + $OSArchitecture }
}
if ([string]::IsNullOrWhiteSpace($OSName)) {
$OSName = (($OS.Caption -replace '^Microsoft\s+', '') -replace '[\\/:*?"<>|]', '').Trim() + ' ' + $OSArchitecture
}
Write-Output $OSName
}
Function Get-RegistryValue {
param (
[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Path,
[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Name
)
Return (Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name
}
Function Set-RegistryValue {
param (
[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Path,
[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Name,
[parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$Value,
[ValidateSet("String","ExpandString","Binary","DWord","MultiString","Qword")]$ProperyType="String"
)
#Make sure the key exists
If (!(Test-Path $Path)){
New-Item $Path -Force | Out-Null
}
New-ItemProperty -Force -Path $Path -Name $Name -Value $Value -PropertyType $ProperyType | Out-Null
}
Function Get-Sitecode {
try {
<#
if ($PowerShellVersion -ge 6) { $obj = (Invoke-CimMethod -Namespace "ROOT\ccm" -ClassName SMS_Client -MethodName GetAssignedSite).sSiteCode }
else { $obj = $([WmiClass]"ROOT\ccm:SMS_Client").getassignedsite() | Select-Object -Expandproperty sSiteCode }
#>
$sms = new-object -comobject 'Microsoft.SMS.Client'
$obj = $sms.GetAssignedSite()
}
catch { $obj = '...' }
finally { Write-Output $obj }
}
Function Get-ClientVersion {
try {
$obj = (Get-CimInstance -Namespace root/ccm -ClassName SMS_Client -ErrorAction Stop).ClientVersion
}
catch { $obj = $null }
finally { Write-Output $obj }
}
# String comparison orders '5.00.10000.1000' below '5.00.9135.1000'.
Function ConvertTo-ClientVersion {
Param([Parameter(Mandatory=$false)]$Value)
$parsed = $null
if ([System.Version]::TryParse(([string]$Value).Trim(), [ref]$parsed)) { return $parsed }
return $null
}
# Returns $true when Installed is at least Minimum. An unreadable installed version fails the check;
# an unreadable or empty minimum passes it.
Function Test-ClientVersionAtLeast {
Param($Installed, $Minimum)
$min = ConvertTo-ClientVersion $Minimum
if ($null -eq $min) { return $true }
$inst = ConvertTo-ClientVersion $Installed
if ($null -eq $inst) { return $false }
return ($inst -ge $min)
}
Function Get-ClientCache {
try {
$obj = (New-Object -ComObject UIResource.UIResourceMgr).GetCacheInfo().TotalSize
#if ($PowerShellVersion -ge 6) { $obj = (Get-CimInstance -Namespace "ROOT\CCM\SoftMgmtAgent" -Class CacheConfig -ErrorAction SilentlyContinue).Size }
#else { $obj = (Get-WmiObject -Namespace "ROOT\CCM\SoftMgmtAgent" -Class CacheConfig -ErrorAction SilentlyContinue).Size }
}
catch { $obj = 0}
finally {
if ($null -eq $obj) { $obj = 0 }
Write-Output $obj
}
}
Function Get-ClientMaxLogSize {
try { $obj = [Math]::Round(((Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\CCM\Logging\@Global').LogMaxSize) / 1000) }
catch { $obj = 0 }
finally { Write-Output $obj }
}
Function Get-ClientMaxLogHistory {
try { $obj = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\CCM\Logging\@Global').LogMaxHistory }
catch { $obj = 0 }
finally { Write-Output $obj }
}
Function Get-Domain {
try {
$obj = (Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop).Domain
}
catch { $obj = $null }
finally { Write-Output $obj }
}
Function Get-CCMLogDirectory {
$obj = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\CCM\Logging\@Global').LogDirectory
if ($null -eq $obj) { $obj = "$env:SystemDrive\windows\ccm\Logs" }
Write-Output $obj
}
Function Get-CCMDirectory {
$obj = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\SMS\Client\Configuration\Client Properties' -Name 'Local SMS Path' -ErrorAction SilentlyContinue).'Local SMS Path'
if ([string]::IsNullOrWhiteSpace($obj)) { $obj = Join-Path $env:windir 'CCM' }
Write-Output ($obj.TrimEnd('\'))
}
<#
.SYNOPSIS
Function to test if local database files are missing from the ConfigMgr client.
.DESCRIPTION
Function to test if local database files are missing from the ConfigMgr client. Will tag client for reinstall if less than 7. Returns $True if compliant or $False if non-compliant
.EXAMPLE
An example
.NOTES
Returns $True if compliant or $False if non-compliant. Non.compliant computers require remediation and will be tagged for ConfigMgr client reinstall.
#>
Function Test-CcmSDF {
$ccmdir = Get-CCMDirectory
$files = @(Get-ChildItem "$ccmdir\*.sdf" -ErrorAction SilentlyContinue)
if ($files.Count -lt 7) { $obj = $false }
else { $obj = $true }
Write-Output $obj
}
# Report only. Current clients write CcmSQLCE.log at the default log level during normal operation,
# so the log alone does not prove database damage; acting on it uninstalls healthy clients.
Function Test-CcmSQLCELog {
$logdir = Get-CCMLogDirectory
$logFile = "$logdir\CcmSQLCE.log"
$logLevel = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\CCM\Logging\@Global' -ErrorAction SilentlyContinue).logLevel
if ((Test-Path -Path $logFile) -and ($logLevel -ne 0)) {
$file = Get-Item -Path $logFile
$now = Get-Date
if ((($now - $file.LastWriteTime).Days -lt 7) -and (($now - $file.CreationTime).Days -gt 7)) {
Write-Warning "CcmSQLCE.log is active outside debug logging. Review it for SQL CE errors. No remediation."
}
}
Write-Output $false
}
function Test-CCMCertificateError {
Param(
[Parameter(Mandatory=$true)]$Log,
[datetime]$StartTime = [datetime]::MinValue
)
# Since client 2107 the self-signed certificate is bound to a hardware key storage provider and is
# not exportable, so no key file is deleted. Only lines written since the last run count, which
# stops one old log line from triggering the same action on every run.
$entries = @(Get-CMLogEntry -LogFile (Join-Path (Get-CCMLogDirectory) 'ClientIDManagerStartup.log') -StartTime $StartTime)
$missing = @($entries | Where-Object { $_.Message.Contains('Failed to find the certificate in the store') }).Count -gt 0
$rejected = @($entries | Where-Object { $_.Message.Contains('Server rejected registration') }).Count -gt 0
if (-not $missing -and -not $rejected) {
Write-Output 'ConfigMgr Client Certificate: OK'
$log.ClientCertificate = 'OK'
return $false
}
if ($rejected) {
$log.ClientCertificate = 'Registration rejected'
Add-Finding -Log $Log -Text 'Site rejected the client registration'
}
if ($missing) {
$log.ClientCertificate = 'Certificate missing'
if ((ConvertTo-ConfigBoolean (Get-XMLConfigRemediationClientCertificate)) -and -not $script:MonitorOnly) {
Write-Warning 'ConfigMgr Client Certificate: certificate missing. Tagging the client for reinstall.'
New-ClientInstalledReason -Log $Log -Message 'Client certificate missing.'
return $true
}
Add-Finding -Log $Log -Text 'Client certificate missing from the store'
}
return $false
}
Function Test-InTaskSequence {
try { $tsenv = New-Object -COMObject Microsoft.SMS.TSEnvironment }
catch { $tsenv = $null }
if ($tsenv) {
Write-Host "Configuration Manager Task Sequence detected on computer. Exiting script"
Exit 2
}
}
Function Test-BITS {
Param([Parameter(Mandatory=$true)]$Log)
if ($BitsCheckEnabled -ne $true) {
Write-Host "BITS: PowerShell Module BitsTransfer missing. Skipping check"
$log.BITS = "PS Module BitsTransfer missing"
return $false
}
# BITS retries TransientError jobs by itself; only Error is a final state that needs an action.
# The BITS service security descriptor is never changed: Windows ships its own default.
$days = Get-ConfigOption -Name 'BITSCheck' -Property 'Days' -Default 7
$limit = (Get-Date).AddDays(-$days)
$stuck = @(Get-BitsTransfer -AllUsers -ErrorAction SilentlyContinue | Where-Object { $_.JobState -eq 'Error' -and $_.CreationTime -lt $limit })
if ($stuck.Count -eq 0) {
Write-Host "BITS: OK"
$log.BITS = 'OK'
return $false
}
if ((ConvertTo-ConfigBoolean (Get-XMLConfigBITSCheckFix)) -and -not $script:MonitorOnly) {
$stuck | Remove-BitsTransfer -ErrorAction SilentlyContinue
Write-Host "BITS: removed $($stuck.Count) job(s) in Error state for more than $days days"
$log.BITS = 'Remediated'
return $true
}
Write-Host "BITS: $($stuck.Count) job(s) in Error state for more than $days days. Monitor only"
$log.BITS = 'Error'
return $false
}
Function Test-ClientSettingsConfiguration {
Param([Parameter(Mandatory=$true)]$Log)
$ClientSettingsConfig = @(Get-CimInstance -Namespace "root\ccm\Policy\DefaultMachine\RequestedConfig" -ClassName CCM_ClientAgentConfig -ErrorAction SilentlyContinue | Where-Object {$_.PolicySource -eq "CcmTaskSequence"})
if ($ClientSettingsConfig.Count -gt 0) {
$fix = ([string](Get-XMLConfigClientSettingsCheckFix)).ToLower()
if ($fix -eq "true") {
$text = "ClientSettings: Error. Remediating"
$attempt = 0
DO {
$attempt++
Get-CimInstance -Namespace "root\ccm\Policy\DefaultMachine\RequestedConfig" -ClassName CCM_ClientAgentConfig | Where-Object {$_.PolicySource -eq "CcmTaskSequence"} | Select-Object -first 1000 | Remove-CimInstance -ErrorAction SilentlyContinue
$remaining = Get-CimInstance -Namespace "root\ccm\Policy\DefaultMachine\RequestedConfig" -ClassName CCM_ClientAgentConfig | Where-Object {$_.PolicySource -eq "CcmTaskSequence"} | Select-Object -first 1
} Until ((-not $remaining) -or ($attempt -ge 10))
if ($remaining) {
$text = "ClientSettings: Error. Task sequence client settings remain after $attempt removal attempts"
$log.ClientSettings = 'Error'
}
else { $log.ClientSettings = 'Remediated' }
$obj = $true
}
else {
$text = "ClientSettings: Error. Monitor only"
$log.ClientSettings = 'Error'
$obj = $false
}
}
else {
$text = "ClientSettings: OK"
$log.ClientSettings = 'OK'
$Obj = $false
}
Write-Host $text
#Write-Output $Obj
}
Function New-ClientInstalledReason {
Param(
[Parameter(Mandatory=$true)]$Message,
[Parameter(Mandatory=$true)]$Log
)
if ($null -eq $log.ClientInstalledReason) { $log.ClientInstalledReason = $Message }
else { $log.ClientInstalledReason += " $Message" }
}
Function Get-OSDiskFreeSpace {
$driveC = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object {$_.DeviceID -eq "$env:SystemDrive"} | Select-Object FreeSpace, Size
$freeSpace = (($driveC.FreeSpace / $driveC.Size) * 100)
Write-Output ([math]::Round($freeSpace,2))
}
Function Get-LastInstalledPatches {
Param([Parameter(Mandatory=$true)]$Log)
# Reading date from Windows Update COM object.
$Session = New-Object -ComObject Microsoft.Update.Session
$Searcher = $Session.CreateUpdateSearcher()
$HistoryCount = $Searcher.GetTotalHistoryCount()
# Windows 10, 11 and Server 2016-2025 record installs by UpdateOrchestrator or the ConfigMgr client.
$Date = $Searcher.QueryHistory(0, $HistoryCount) | Where-Object {
($_.ClientApplicationID -eq 'UpdateOrchestrator' -or $_.ClientApplicationID -eq 'ccmexec') -and ($_.Title -notmatch "Security Intelligence Update|Definition Update")
} | Select-Object -ExpandProperty Date | Measure-Latest
# IUpdateHistoryEntry.Date is UTC with Kind Unspecified; Get-SmallDateTime expects local time.
if ($Date -is [datetime]) { $Date = [DateTime]::SpecifyKind($Date, [DateTimeKind]::Utc).ToLocalTime() }
$Hotfix = Get-CimInstance -ClassName Win32_QuickFixEngineering | Where-Object { $_.InstalledOn } | Select-Object @{Name="InstalledOn";Expression={[DateTime]::Parse($_.InstalledOn,$([System.Globalization.CultureInfo]::GetCultureInfo("en-US")))}}
$Hotfix = $Hotfix | Select-Object -ExpandProperty InstalledOn
$Date2 = $null
if ($null -ne $hotfix) { $Date2 = Get-Date($hotfix | Measure-Latest) -ErrorAction SilentlyContinue }
if (($Date -ge $Date2) -and ($null -ne $Date)) { $Log.OSUpdates = Get-SmallDateTime -Date $Date }
elseif (($Date2 -gt $Date) -and ($null -ne $Date2)) { $Log.OSUpdates = Get-SmallDateTime -Date $Date2 }
}
function Measure-Latest {
BEGIN { $latest = $null }
PROCESS { if (($null -ne $_) -and (($null -eq $latest) -or ($_ -gt $latest))) { $latest = $_ } }
END { $latest }
}
Function Test-LogFileHistory {
Param([Parameter(Mandatory=$true)]$Logfile)
$startString = '<--- ConfigMgr Client Health Check starting --->'
$content = ''
# Handle the network share log file
if (Test-Path $logfile -ErrorAction SilentlyContinue) { $content = Get-Content $logfile -ErrorAction SilentlyContinue }
else { return }
$maxHistory = ConvertTo-ConfigInt -Value (Get-XMLConfigLoggingMaxHistory) -Default 8 -Minimum 1
$startCount = [regex]::matches($content,$startString).count
# Delete logfile if more start and stop entries than max history
if ($startCount -ge $maxHistory) { Remove-Item $logfile -Force }
}
Function Test-DNSConfiguration {
Param([Parameter(Mandatory=$true)]$Log)
#$dnsdomain = (Get-WmiObject Win32_NetworkAdapterConfiguration -filter "ipenabled = 'true'").DNSDomain
$fqdn = [System.Net.Dns]::GetHostEntry([string]"localhost").HostName
$localIPs = Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration | Where-Object {$_.IPEnabled -Match "True"} | Select-Object -ExpandProperty IPAddress
$dnscheck = [System.Net.DNS]::GetHostByName($fqdn)
$OSName = Get-OperatingSystem
if (($OSName -notlike "*Windows 7*") -and ($OSName -notlike "*Server 2008*")) {
# This method is supported on Windows 8 / Server 2012 and higher. More acurate than using .NET object method
try {
$ActiveAdapters = (get-netadapter | Where-Object {$_.Status -like "Up"}).Name
$dnsServers = Get-DnsClientServerAddress | Where-Object {$ActiveAdapters -contains $_.InterfaceAlias} | Where-Object {$_.AddressFamily -eq 2} | Select-Object -ExpandProperty ServerAddresses
$dnsAddressList = Resolve-DnsName -Name $fqdn -Server ($dnsServers | Select-Object -First 1) -Type A -DnsOnly | Select-Object -ExpandProperty IPAddress
}
catch {
# Fallback to depreciated method
$dnsAddressList = $dnscheck.AddressList | Select-Object -ExpandProperty IPAddressToString
$dnsAddressList = $dnsAddressList -replace("%(.*)", "")
}
}
else {
# This method cannot guarantee to only resolve against DNS sever. Local cache can be used in some circumstances.
# For Windows 7 only
$dnsAddressList = $dnscheck.AddressList | Select-Object -ExpandProperty IPAddressToString
$dnsAddressList = $dnsAddressList -replace("%(.*)", "")
}
$dnsFail = ''
$logFail = ''
Write-Verbose 'Verify that local machines FQDN matches DNS'
if ($dnscheck.HostName -like $fqdn) {
$obj = $true
Write-Verbose 'Checking if one local IP matches on IP from DNS'
Write-Verbose 'Loop through each IP address published in DNS'
foreach ($dnsIP in $dnsAddressList) {
#Write-Host "Testing if IP address: $dnsIP published in DNS exist in local IP configuration."
##if ($dnsIP -notin $localIPs) { ## Requires PowerShell 3. Works fine :(
if ($localIPs -notcontains $dnsIP) {
$dnsFail += "IP '$dnsIP' in DNS record do not exist locally`n"
$logFail += "$dnsIP "
$obj = $false
}
}
}
else {
$hn = $dnscheck.HostName
$dnsFail = 'DNS name: ' +$hn + ' local fqdn: ' +$fqdn + ' DNS IPs: ' +$dnsAddressList + ' Local IPs: ' + $localIPs
$logFail = "Hostname mismatch: $hn"
$obj = $false
Write-Host $dnsFail
}
$FileLogLevel = ([string](Get-XMLConfigLoggingLevel)).ToLower()
switch ($obj) {
$false {
$fix = ([string](Get-XMLConfigDNSFix)).ToLower()
# Registration does nothing when policy or every adapter turns dynamic DNS update off.
$policyRegistration = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient' -Name RegistrationEnabled -ErrorAction SilentlyContinue).RegistrationEnabled
$registeringAdapters = @(Get-DnsClient -ErrorAction SilentlyContinue | Where-Object { $_.RegisterThisConnectionsAddress })
if (($fix -eq "true") -and (($policyRegistration -eq 0) -or ($registeringAdapters.Count -eq 0))) {
$log.DNS = $logFail
Add-Finding -Log $Log -Text 'DNS mismatch; dynamic DNS registration is turned off'
}
elseif ($fix -eq "true") {
$text = 'DNS Check: FAILED. IP address published in DNS do not match IP address on local machine. Trying to resolve by registerting with DNS server'
Register-DnsClient | Out-Null
Write-Host $text
$log.DNS = $logFail
if (-NOT($FileLogLevel -like "clientlocal")) {
Out-LogFile -Xml $xml -Text $text -Severity 2
Out-LogFile -Xml $xml -Text $dnsFail -Severity 2
}
}
else {
$text = 'DNS Check: FAILED. IP address published in DNS do not match IP address on local machine. Monitor mode only, no remediation'
$log.DNS = $logFail
if (-NOT($FileLogLevel -like "clientlocal")) { Out-LogFile -Xml $xml -Text $text -Severity 2}
Write-Host $text
}
}
$true {
$text = 'DNS Check: OK'
Write-Output $text
$log.DNS = 'OK'
}
}
#Write-Output $obj
}
# Function to test that 'HKU:\S-1-5-18\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\' is set to '%USERPROFILE%\AppData\Roaming'. CCMSETUP will fail if not.
# Reference: https://www.systemcenterdudes.com/could-not-access-network-location-appdata-ccmsetup-log/
Function Test-CCMSetup1 {
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS -ErrorAction SilentlyContinue | Out-Null
$correctValue = '%USERPROFILE%\AppData\Roaming'
$currentValue = (Get-Item 'HKU:\S-1-5-18\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\').GetValue('AppData', $null, 'DoNotExpandEnvironmentNames')
# Only fix if the value is wrong
if ($currentValue -ne $correctValue) { Set-ItemProperty -Path 'HKU:\S-1-5-18\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\' -Name 'AppData' -Value $correctValue }
}
Function Test-Update {
Param([Parameter(Mandatory=$true)]$Log)
$UpdateShare = Get-XMLConfigUpdatesShare