# Clearing SCOM Agent Cache by N.I
# Note: Run this script with administrative privileges to access remote server C$ share
$Server = Read-Host "Please enter your server name"
$Service = Get-Service -Name HealthService -ComputerName $Server
$timeout = 30 # seconds
try {
Write-Host "1. Stopping the Monitoring Agent service...`n"
if ($Service.Status -eq 'Running') {
Stop-Service $Service
$startTime = Get-Date
while ($Service.Status -ne 'Stopped' -and (Get-Date) -lt $startTime.AddSeconds($timeout)) {
Start-Sleep -s 1
$Service = Get-Service -Name HealthService -ComputerName $Server
}
if ($Service.Status -ne 'Stopped') {
Write-Host "Failed to stop the service within $timeout seconds." -ForegroundColor Red
throw "Service stop timeout."
}
Write-Host "Service stopped successfully." -ForegroundColor Green
} else {
Write-Host "Service is not running." -ForegroundColor Yellow
}
Write-Host "`n2. Checking the Monitoring Agent service status:"
Write-Host "`nMonitoring Agent service status: " -NoNewline
Write-Host $Service.Status -ForegroundColor Yellow
Write-Host "`n3. Renaming the existing 'Health Service State' folder to 'Health Service State Old'`n"
$HealthServiceStatePath = "\\$Server\C$\Program Files\Microsoft Monitoring Agent\Agent\Health Service State"
if (Test-Path $HealthServiceStatePath) {
Rename-Item -Path $HealthServiceStatePath -NewName "Health Service State Old"
if (Test-Path "\\$Server\C$\Program Files\Microsoft Monitoring Agent\Agent\Health Service State Old") {
Write-Host "Folder renamed successfully." -ForegroundColor Green
} else {
Write-Host "Failed to rename folder." -ForegroundColor Red
throw "Rename operation failed."
}
} else {
Write-Host "Health Service State folder not found." -ForegroundColor Yellow
}
Write-Host "`n4. Starting the Monitoring Agent service…`n"
Start-Service $Service
$startTime = Get-Date
while ($Service.Status -ne 'Running' -and (Get-Date) -lt $startTime.AddSeconds($timeout)) {
Start-Sleep -s 1
$Service = Get-Service -Name HealthService -ComputerName $Server
}
if ($Service.Status -ne 'Running') {
Write-Host "Failed to start the service within $timeout seconds." -ForegroundColor Red
} else {
Write-Host "Service started successfully." -ForegroundColor Green
}
Write-Host "`n5. Checking the Monitoring Agent service status:"
Write-Host "`nMonitoring Agent service status: " -NoNewline
Write-Host $Service.Status -ForegroundColor Green
Write-Host "`n6. Removing the 'Health Service State Old' folder."
$OldHealthServiceStatePath = "\\$Server\C$\Program Files\Microsoft Monitoring Agent\Agent\Health Service State Old"
if (Test-Path $OldHealthServiceStatePath) {
Remove-Item -Path $OldHealthServiceStatePath -Recurse -Force
Write-Host "Old folder removed successfully." -ForegroundColor Green
} else {
Write-Host "Health Service State Old folder not found." -ForegroundColor Yellow
}
Write-Host "`n7. Done!" -ForegroundColor Green
}
catch {
Write-Host "An error occurred: $_" -ForegroundColor Red
}