forked from AndersRodland/ConfigMgrClientHealth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfigMgrClientHealth.ps1
3166 lines (2705 loc) · 141 KB
/
ConfigMgrClientHealth.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
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.Xml
.EXAMPLE
\\cm01.rodland.lab\ClientHealth$\ConfigMgrClientHealth.ps1 -Config \\cm01.rodland.lab\ClientHealth$\Config.Xml -Webservice https://cm01.rodland.lab/ConfigMgrClientHealth
.PARAMETER Config
A single parameter specifying the path to the configuration XML file.
.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 XML Configuration File')]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[ValidatePattern('.xml$')]
[string]$Config,
[Parameter(HelpMessage='URI to ConfigMgr Client Health Webservice')]
[string]$Webservice
)
Begin {
# ConfigMgr Client Health Version
$Version = '0.8.1'
$PowerShellVersion = [int]$PSVersionTable.PSVersion.Major
$global:ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
#If no config file was passed in, use the default.
If (!$Config){$Config = Join-Path ($global:ScriptPath) "Config.xml"}
Write-Verbose "Script version: $Version"
Write-Verbose "PowerShell version: $PowerShellVersion"
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 XML file
if (Test-Path $Config) {
# 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
}
}
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
try {
Import-Module BitsTransfer -ErrorAction stop
$BitsCheckEnabled = $true
}
catch { $BitsCheckEnabled = $false }
#region functions
Function Get-DateTime {
$format = (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 }
Write-Output $Obj
}
# Update-WebService use ClientHealth Webservice to update database. RESTful API.
Function Update-Webservice {
Param([Parameter(Mandatory=$true)][String]$URI, $Log)
$Hostname = Get-Hostname
$Obj = $Log | ConvertTo-Json
$URI = $URI + "/Clients"
$ContentType = "application/json"
# Detect if we use PUT or POST
try {
Invoke-RestMethod -Uri "$URI/$Hostname" | Out-Null
$Method = "PUT"
$URI = $URI + "/$Hostname"
}
catch { $Method = "POST" }
try { Invoke-RestMethod -Method $Method -Uri $URI -Body $Obj -ContentType $ContentType | Out-Null }
catch {
$ExceptionMessage = $_.Exception.Message
Write-Host "Error Invoking RestMethod $Method on URI $URI. Failed to update database using webservice. Exception: $ExceptionMessage"
}
}
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{
if ($PowerShellVersion -ge 6) { $ServiceProcessID = (Get-CimInstance Win32_Service -Filter "Name='$($Name)'").ProcessID }
else { $ServiceProcessID = (Get-WMIObject -Class 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.
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])"
}
#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)."
Return
}
#Loop through each search string looking for a match.
ForEach($String in $SearchStrings){
If ($LogMessage -match $String){return $LogData[$i]}
}
}
#Looped through log file without finding a match.
Return
}
Function Test-LocalLogging {
$clientpath = Get-LocalFilesPath
if ((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)
if ($Mode -like "Local") {
Test-LocalLogging
$clientpath = Get-LocalFilesPath
$Logfile = "$clientpath\ClientHealth.log"
}
else { $Logfile = Get-LogFileName }
if ($mode -like "ClientInstall" ) { $text = "ConfigMgr Client installation failed. Agent not detected 10 minutes after triggering installation." }
$obj = '[' +(Get-DateTime) +'] '+$text
$obj | Out-File -Encoding utf8 -Append $logFile
}
Function Get-OperatingSystem {
if ($PowerShellVersion -ge 6) { $OS = Get-CimInstance Win32_OperatingSystem }
else { $OS = Get-WmiObject 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}
"*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 }
}
Write-Output $OSName
}
Function Get-MissingUpdates {
$UpdateShare = Get-XMLConfigUpdatesShare
$OSName = Get-OperatingSystem
$build = $null
if ($OSName -like "*Windows 10*") {
$build = Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber
switch ($build) {
10240 {$OSName = $OSName + " 1507"}
10586 {$OSName = $OSName + " 1511"}
14393 {$OSName = $OSName + " 1607"}
15063 {$OSName = $OSName + " 1703"}
16299 {$OSName = $OSName + " 1709"}
17134 {$OSName = $OSName + " 1803"}
default {$OSName = $OSName + " Insider Preview"}
}
}
$Updates = $UpdateShare + "\" + $OSName + "\"
$obj = New-Object PSObject @{}
If ((Test-Path $Updates) -eq $true) {
$regex = "\b(?!(KB)+(\d+)\b)\w+"
$hotfixes = (Get-ChildItem $Updates | Select-Object -ExpandProperty Name)
if ($PowerShellVersion -ge 6) { $installedUpdates = (Get-CimInstance -ClassName Win32_QuickFixEngineering).HotFixID }
else { $installedUpdates = Get-Hotfix | Select-Object -ExpandProperty HotFixID }
foreach ($hotfix in $hotfixes) {
$kb = $hotfix -replace $regex -replace "\." -replace "-"
if ($installedUpdates -like $kb) {}
else { $obj.Add('Hotfix', $hotfix) }
}
}
Write-Output $obj
}
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 {
if ($PowerShellVersion -ge 6) { $obj = (Get-CimInstance -Namespace root/ccm SMS_Client).ClientVersion }
else { $obj = (Get-WmiObject -Namespace root/ccm SMS_Client).ClientVersion }
}
catch { $obj = $false }
finally { Write-Output $obj }
}
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 {
if ($PowerShellVersion -ge 6) { $obj = (Get-CimInstance Win32_ComputerSystem).Domain }
else { $obj = (Get-WmiObject Win32_ComputerSystem).Domain }
}
catch { $obj = $false }
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 {
$logdir = Get-CCMLogDirectory
$obj = $logdir.replace("\Logs", "")
Write-Output $obj
}
<#
.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"
if ($files.Count -lt 7) { $obj = $false }
else { $obj = $true }
Write-Output $obj
}
Function Test-CcmSQLCELog {
$logdir = Get-CCMLogDirectory
$ccmdir = Get-CCMDirectory
$logFile = "$logdir\CcmSQLCE.log"
$logLevel = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\CCM\Logging\@Global').logLevel
if ( (Test-Path -Path $logFile) -and ($logLevel -ne 0) ) {
# Not in debug mode, and CcmSQLCE.log exists. This could be bad.
$LastWriteTime = (Get-ChildItem $logFile).LastWriteTime
$CreationTime = (Get-ChildItem $logFile).CreationTime
$FileDate = Get-Date($LastWriteTime)
$FileCreated = Get-Date($CreationTime)
$now = Get-Date
if ( (($now - $FileDate).Days -lt 7) -and ((($now - $FileCreated).Days) -gt 7) ) {
$text = "CM client not in debug mode, and CcmSQLCE.log exists. This is very bad. Cleaning up local SDF files and reinstalling CM client"
Write-Host $text -ForegroundColor Red
# Delete *.SDF Files
$Service = Get-Service -Name ccmexec
$Service.Stop()
$seconds = 0
Do {
Start-Sleep -Seconds 1
$seconds++
} while ( ($Service.Status -ne "Stopped") -and ($seconds -le 60) )
# Do another test to make sure CcmExec service really is stopped
if ($Service.Status -ne "Stopped") { Stop-Service -Name ccmexec -Force }
Write-Verbose "Waiting 10 seconds to allow file locking issues to clear up"
Start-Sleep -seconds 10
try {
$files = Get-ChildItem "$ccmdir\*.sdf"
$files | Remove-Item -Force | Out-Null
Remove-Item -Path $logFile -Force | Out-Null
}
catch {
Write-Verbose "Obviously that wasn't enough time"
Start-Sleep -Seconds 30
# We try again
$files = Get-ChildItem "$ccmdir\*.sdf"
$files | Remove-Item -Force | Out-Null
Remove-Item -Path $logFile -Force | Out-Null
}
$obj = $true
}
# CcmSQLCE.log has not been updated for two days. We are good for now.
else { $obj = $false }
}
# we are good
else { $obj = $false }
Write-Output $obj
}
function Test-CCMCertificateError {
Param([Parameter(Mandatory=$true)]$Log)
# More checks to come
$logdir = Get-CCMLogDirectory
$logFile1 = "$logdir\ClientIDManagerStartup.log"
$error1 = 'Failed to find the certificate in the store'
$error2 = '[RegTask] - Server rejected registration 3'
$content = Get-Content -Path $logFile1
$ok = $true
if ($content -match $error1) {
$ok = $false
$text = 'ConfigMgr Client Certificate: Error failed to find the certificate in store. Attempting fix.'
Write-Warning $text
Stop-Service -Name ccmexec -Force
# Name is persistant across systems.
$cert = "$env:ProgramData\Microsoft\Crypto\RSA\MachineKeys\19c5cf9c7b5dc9de3e548adb70398402_50e417e0-e461-474b-96e2-077b80325612"
# CCM creates new certificate when missing.
Remove-Item -Path $cert -Force -ErrorAction SilentlyContinue | Out-Null
# Remove the error from the logfile to avoid double remediations based on false positives
$newContent = $content | Select-String -pattern $Error1 -notmatch
Out-File -FilePath $logfile -InputObject $newContent -Encoding utf8 -Force
Start-Service -Name ccmexec
# Update log object
$log.ClientCertificate = $error1
}
#$content = Get-Content -Path $logFile2
if ($content -match $error2) {
$ok = $false
$text = 'ConfigMgr Client Certificate: Error! Server rejected client registration. Client Certificate not valid. No auto-remediation.'
Write-Error $text
$log.ClientCertificate = $error2
}
if ($ok = $true) {
$text = 'ConfigMgr Client Certificate: OK'
Write-Output $text
$log.ClientCertificate = 'OK'
}
}
Function Test-BITS {
Param([Parameter(Mandatory=$true)]$Log)
if ($BitsCheckEnabled -eq $true) {
$Errors = Get-BitsTransfer -AllUsers | Where-Object { ($_.JobState -like "TransientError") -or ($_.JobState -like "Transient_Error") -or ($_.JobState -like "Error") }
if ($null -ne $Errors) {
$fix = (Get-XMLConfigBITSCheckFix).ToLower()
if ($fix -eq "true") {
$text = "BITS: Error. Remediating"
$Errors | Remove-BitsTransfer -ErrorAction SilentlyContinue
Invoke-Expression -Command 'sc.exe sdset bits "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)"' | out-null
$log.BITS = 'Remediated'
$obj = $true
}
else {
$text = "BITS: Error. Monitor only"
$log.BITS = 'Error'
$obj = $false
}
}
else {
$text = "BITS: OK"
$log.BITS = 'OK'
$Obj = $false
}
}
else {
$text = "BITS: PowerShell Module BitsTransfer missing. Skipping check"
$log.BITS = "PS Module BitsTransfer missing"
$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-PendingReboot {
$result = @{
CBSRebootPending =$false
WindowsUpdateRebootRequired = $false
FileRenamePending = $false
SCCMRebootPending = $false
}
#Check CBS Registry
$key = Get-ChildItem "HKLM:Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending" -ErrorAction SilentlyContinue
if ($null -ne $key) { $result.CBSRebootPending = $true }
#Check Windows Update
$key = Get-Item 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' -ErrorAction SilentlyContinue
if ($null -ne $key) { $result.WindowsUpdateRebootRequired = $true }
#Check PendingFileRenameOperations
$prop = Get-ItemProperty 'HKLM:SYSTEM\CurrentControlSet\Control\Session Manager' -Name PendingFileRenameOperations -ErrorAction SilentlyContinue
if ($null -ne $prop)
{
#PendingFileRenameOperations is not *must* to reboot?
#$result.FileRenamePending = $true
}
try
{
$util = [wmiclass]'\\.\root\ccm\clientsdk:CCM_ClientUtilities'
$status = $util.DetermineIfRebootPending()
if(($null -ne $status) -and $status.RebootPending){ $result.SCCMRebootPending = $true }
}
catch{}
#Return Reboot required
if ($result.ContainsValue($true)) {
#$text = 'Pending Reboot: YES'
$obj = $true
$log.PendingReboot = 'Pending Reboot'
}
else {
$obj = $false
$log.PendingReboot = 'OK'
}
Write-Output $obj
}
Function Get-ProvisioningMode {
$registryPath = 'HKLM:\SOFTWARE\Microsoft\CCM\CcmExec'
$provisioningMode = (Get-ItemProperty -Path $registryPath).ProvisioningMode
if ($provisioningMode -eq 'true') { $obj = $true }
else { $obj = $false }
Write-Output $obj
}
Function Get-OSDiskFreeSpace {
if ($PowerShellVersion -ge 6) { $driveC = Get-CimInstance -Class Win32_LogicalDisk | Where-Object {$_.DeviceID -eq "$env:SystemDrive"} | Select-Object FreeSpace, Size }
else { $driveC = Get-WmiObject -Class 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-Computername {
if ($PowerShellVersion -ge 6) { $obj = (Get-CimInstance Win32_ComputerSystem).Name }
else { $obj = (Get-WmiObject Win32_ComputerSystem).Name }
Write-Output $obj
}
Function Get-LastBootTime {
if ($PowerShellVersion -ge 6) { $wmi = Get-CimInstance Win32_OperatingSystem }
else { $wmi = Get-WmiObject Win32_OperatingSystem }
$obj = $wmi.ConvertToDateTime($wmi.LastBootUpTime)
Write-Output $obj
}
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()
$OS = Get-OperatingSystem
Switch -Wildcard ($OS) {
"*Windows 7*" {
$Date = $Searcher.QueryHistory(0, $HistoryCount) | Where-Object {
($_.ClientApplicationID -eq 'AutomaticUpdates' -or $_.ClientApplicationID -eq 'ccmexec') -and ($_.Title -notmatch "Definition Update")
} | Select-Object -ExpandProperty Date | Measure-Latest
}
"*Windows 8*" {
$Date = $Searcher.QueryHistory(0, $HistoryCount) | Where-Object {
($_.ClientApplicationID -eq 'AutomaticUpdatesWuApp' -or $_.ClientApplicationID -eq 'ccmexec') -and ($_.Title -notmatch "Definition Update")
} | Select-Object -ExpandProperty Date | Measure-Latest
}
"*Windows 10*" {
$Date = $Searcher.QueryHistory(0, $HistoryCount) | Where-Object {
($_.ClientApplicationID -eq 'UpdateOrchestrator' -or $_.ClientApplicationID -eq 'ccmexec') -and ($_.Title -notmatch "Definition Update")
} | Select-Object -ExpandProperty Date | Measure-Latest
}
"*Server 2008*" {
$Date = $Searcher.QueryHistory(0, $HistoryCount) | Where-Object {
($_.ClientApplicationID -eq 'AutomaticUpdates' -or $_.ClientApplicationID -eq 'ccmexec') -and ($_.Title -notmatch "Definition Update")
} | Select-Object -ExpandProperty Date | Measure-Latest
}
"*Server 2012*" {
$Date = $Searcher.QueryHistory(0, $HistoryCount) | Where-Object {
($_.ClientApplicationID -eq 'AutomaticUpdatesWuApp' -or $_.ClientApplicationID -eq 'ccmexec') -and ($_.Title -notmatch "Definition Update")
} | Select-Object -ExpandProperty Date | Measure-Latest
}
"*Server 2016*" {
$Date = $Searcher.QueryHistory(0, $HistoryCount) | Where-Object {
($_.ClientApplicationID -eq 'UpdateOrchestrator' -or $_.ClientApplicationID -eq 'ccmexec') -and ($_.Title -notmatch "Definition Update")
} | Select-Object -ExpandProperty Date | Measure-Latest
}
}
# Reading date from PowerShell Get-Hotfix
#$now = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
#$Hotfix = Get-Hotfix | Where-Object {$_.InstalledOn -le $now} | Select-Object -ExpandProperty InstalledOn -ErrorAction SilentlyContinue
#$Hotfix = Get-Hotfix | Select-Object -ExpandProperty InstalledOn -ErrorAction SilentlyContinue
if ($PowerShellVersion -ge 6) { $Hotfix = Get-CimInstance -ClassName Win32_QuickFixEngineering | Select-Object @{Name="InstalledOn";Expression={[DateTime]::Parse($_.InstalledOn,$([System.Globalization.CultureInfo]::GetCultureInfo("en-US")))}} }
else { $Hotfix = Get-Hotfix | Select-Object @{l="InstalledOn";e={[DateTime]::Parse($_.psbase.properties["installedon"].value,$([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) }
$maxHistory = Get-XMLConfigLoggingMaxHistory
$startCount = [regex]::matches($content,$startString).count
# Delete logfile if more start and stop entries than max history
if ($startCount -ge $maxHistory) { if ((Test-Path -Path $logfile -ErrorAction SilentlyContinue) -eq $true) { 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
if ($PowerShellVersion -ge 6) { $localIPs = Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object {$_.IPEnabled -Match "True"} | Select-Object -ExpandProperty IPAddress }
else { $localIPs = Get-WmiObject 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 {
$AvtiveAdapters = (get-netadapter | Where-Object {$_.Status -like "Up"}).Name
$dnsServers = Get-DnsClientServerAddress | Where-Object {$_.InterfaceAlias -Like $AvtiveAdapters} | 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
$obj = $false
Write-Host $dnsFail
}
$FileLogLevel = ((Get-XMLConfigLogginLevel).ToString()).ToLower()
switch ($obj) {
$false {
$fix = (Get-XMLConfigDNSFix).ToLower()
if ($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'
if ($PowerShellVersion -ge 4) { Register-DnsClient | out-null }
else { ipconfig /registerdns | out-null }
Write-Host $text
$log.DNS = $logFail
if (-NOT($FileLogLevel -like "clientlocal")) {
Out-LogFile -Xml $xml -Text $text
Out-LogFile -Xml $xml -Text $dnsFail
}
}
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 }
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)
#if (($Xml.Configuration.Option | Where-Object {$_.Name -like 'Updates'} | Select-Object -ExpandProperty 'Enable') -like 'True') {
$UpdateShare = Get-XMLConfigUpdatesShare
#$UpdateShare = $Xml.Configuration.Option | Where-Object {$_.Name -like 'Updates'} | Select-Object -ExpandProperty 'Share'
Write-Verbose "Validating required updates is installed on the client. Required updates will be installed if missing on client."
#$OS = Get-WmiObject -class Win32_OperatingSystem
$OSName = Get-OperatingSystem
$build = $null
if ($OSName -like "*Windows 10*") {
$build = Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber
switch ($build) {
10240 {$OSName = $OSName + " 1507"}
10586 {$OSName = $OSName + " 1511"}
14393 {$OSName = $OSName + " 1607"}
15063 {$OSName = $OSName + " 1703"}
16299 {$OSName = $OSName + " 1709"}
17134 {$OSName = $OSName + " 1803"}
default {$OSName = $OSName + " Insider Preview"}
}
}
$Updates = (Join-Path $UpdateShare $OSName)
If ((Test-Path $Updates) -eq $true) {
$regex = "\b(?!(KB)+(\d+)\b)\w+"
$hotfixes = (Get-ChildItem $Updates | Select-Object -ExpandProperty Name)
if ($PowerShellVersion -ge 6) { $installedUpdates = (Get-CimInstance Win32_QuickFixEngineering).HotFixID }
else { $installedUpdates = Get-Hotfix | Select-Object -ExpandProperty HotFixID }
$count = $hotfixes.count
if (($count -eq 0) -or ($count -eq $null)) {
$text = 'Updates: No mandatory updates to install.'
Write-Output $text
$log.Updates = 'OK'
}
else {
$logEntry = $null
foreach ($hotfix in $hotfixes) {
$kb = $hotfix -replace $regex -replace "\." -replace "-"
if ($installedUpdates -like $kb) {
$text = "Update $hotfix" + ": OK"
Write-Output $text
}
else {
if ($null -eq $logEntry) { $logEntry = $kb }
else { $logEntry += ", $kb" }
$fix = (Get-XMLConfigUpdatesFix).ToLower()
if ($fix -eq "true") {
$kbfullpath = Join-Path $updates $hotfix
$text = "Update $hotfix" + ": Missing. Installing now..."
Write-Warning $text
$temppath = Join-Path (Get-LocalFilesPath) "Temp"
If ((Test-Path $temppath) -eq $false) { New-Item -Path $temppath -ItemType Directory | Out-Null }
Copy-Item -Path $kbfullpath -Destination $temppath
$install = Join-Path $temppath $hotfix
wusa.exe $install /quiet /norestart
While (Get-Process wusa -ErrorAction SilentlyContinue) { Start-Sleep -Seconds 2 }
Remove-Item $install -Force -Recurse
}
else {
$text = "Update $hotfix" + ": Missing. Monitor mode only, no remediation."
Write-Warning $text
}
}
if ($null -eq $logEntry) { $log.Updates = 'OK' }
else { $log.Updates = $logEntry }
}
}
}
Else {
$log.Updates = 'Failed'
Write-Warning "Updates Failed: Could not locate update folder '$($Updates)'."
}
}
Function Test-ConfigMgrClient {
Param([Parameter(Mandatory=$true)]$Log)
# Check if the SCCM Agent is installed or not.
# If installed, perform tests to decide if reinstall is needed or not.
if (Get-Service -Name ccmexec -ErrorAction SilentlyContinue) {
$text = "Configuration Manager Client is installed"
Write-Host $text
# Lets not reinstall client unless tests tells us to.
$Reinstall = $false
# We test that the local database files exists. Less than 7 means the client is horrible broken and requires reinstall.
$LocalDBFilesPresent = Test-CcmSDF
if ($LocalDBFilesPresent -eq $False) {
New-ClientInstalledReason -Log $Log -Message "ConfigMgr Client database files missing."
Write-Host "ConfigMgr Client database files missing. Reinstalling..."
# Add /ForceInstall to Client Install Properties to ensure the client is uninstalled before we install client again.
#if (-NOT ($clientInstallProperties -like "*/forceinstall*")) { $clientInstallProperties = $clientInstallProperties + " /forceinstall" }
$Reinstall = $true
$Uninstall = $true
}
# Only test CM client local DB if this check is enabled
$testLocalDB = (Get-XMLConfigCcmSQLCELog).ToLower()
if ($testLocalDB -like "enable") {
Write-Host "Testing CcmSQLCELog"
$LocalDB = Test-CcmSQLCELog
if ($LocalDB -eq $true) {
# LocalDB is messed up
New-ClientInstalledReason -Log $Log -Message "ConfigMgr Client database corrupt."
Write-Host "ConfigMgr Client database corrupt. Reinstalling..."
$Reinstall = $true
$Uninstall = $true
}
}
$CCMService = Get-Service -Name ccmexec -ErrorAction SilentlyContinue
# Reinstall if we are unable to start the CM client
if (($CCMService.Status -eq "Stopped") -and ($LocalDB -eq $false)) {
try {
Write-Host "ConfigMgr Agent not running. Attempting to start it."
if ($CCMService.StartType -ne "Automatic") {
$text = "Configuring service CcmExec StartupType to: Automatic (Delayed Start)..."
Write-Output $text
Set-Service -Name CcmExec -StartupType Automatic
}
Start-Service -Name CcmExec
}
catch {
$Reinstall = $true
New-ClientInstalledReason -Log $Log -Message "Service not running, failed to start."