Public/Clear-SCOMCache.ps1

Function Clear-SCOMCache {
  <#
      .Synopsis
      Will clear SCOM agent cache on local machine
 
      .EXAMPLE
      Clear-SCOMCache -HealthServiceStatePath 'D:\Program Files\Microsoft System Center 2012 R2\Operations Manager\Server\Health Service State'
 
      .EXAMPLE
      Clear-SCOMCache -TimeoutSeconds 60
 
      .INPUTS
      None
 
      .OUTPUTS
      Boolean [true|false]
 
      .NOTES
      Author: Tyson Paul
      Blog: https://monitoringguys.com/
      Version History:
      2020.07.21 - Improved error handling a bit. Added cmdletbinding. Changed outputtype to Bool.
      2020.02.27 - Cleaned up code a bit. Improved logic. Removed WaitSeconds parameter as it was not effective.
      2018.05.25 - Cleaned up. Revised a few things.
 
  #>


  [CmdletBinding(DefaultParameterSetName='Parameter Set 1',
      SupportsShouldProcess=$false,
      PositionalBinding=$false,
      HelpUri = 'http://www.microsoft.com/',
  ConfirmImpact='Medium')]
  [OutputType([BOOL])]

  Param(

    # How many seconds to wait before aborting
    [int]$TimeoutSeconds = 30,

    # If the registry does not contain the correct path you can specify a path here.
    [string]$HealthServiceStatePath = (Join-Path (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Setup" -Name "InstallDirectory").InstallDirectory 'Health Service State' )

  )


  $ServiceName = 'HealthService'
  Write-Verbose "Stopping service: $ServiceName"

  $StartTime = Get-Date
  Try {
    Stop-Service -Name $ServiceName -Verbose -Force -PassThru
    While ( ((Get-Service -Name $ServiceName).Status -ne "Stopped") -AND ((Get-Date) -le ($StartTime.AddSeconds($TimeoutSeconds) )) ) {
      Write-Verbose "Waiting for $ServiceName to stop..."
      Start-Sleep -Seconds 5
    }
  } Catch {
    Write-Warning "Problem while stopping service: $($_). Continuing..."
  }

  If ((Get-Service -Name $ServiceName).Status -ne "Stopped") {
    Write-Warning "Failed to stop service: $ServiceName in the time allowed! Will attempt to leave HealthService in 'Started' state."
    Start-Service $ServiceName -Verbose
    Return $false
  }
  Else {
    Write-Verbose "Attempting to remove cache folder: $HealthServiceStatePath"
    Try {
      Get-Item $HealthServiceStatePath | Remove-Item -Recurse -Force -Verbose -ErrorAction Stop
      Start-Sleep -Seconds 1
    } Catch {
      Write-Warning "Error while deleting cache files. $($_)"
    }
    If (Test-Path -PathType Container $HealthServiceStatePath) {
      Write-Warning "Failed to remove folder: [$($HealthServiceStatePath)] !"
    }
    Else {
      [bool]$folderRemoved = $true
      Write-Verbose "Health Service State folder removed succesfully: [$($HealthServiceStatePath)]."
    }

    $StartTime = Get-Date
    Try {
      Start-Service -Name $ServiceName -Verbose
      While ( ((Get-Service -Name $ServiceName).Status -ne "Running") -AND ((Get-Date) -le ($StartTime.AddSeconds($TimeoutSeconds) )) ) {
        Start-Sleep -Seconds 3
      }
      If ((Get-Service -Name $ServiceName).Status -ne "Running") {
        Write-Warning "Failed to start service: $ServiceName in the time allowed! Verify service manually."
      }
      Else {
        If ( (Test-Path -PathType Container $HealthServiceStatePath) -AND ([bool]$folderRemoved)){
          Write-Verbose "Cache folder auto-created: $HealthServiceStatePath !"
          Write-Verbose "SCOM agent Cache has been cleared."
          Return $true
        }
      }
    } Catch {
      Throw
      Return $false
    }

    If (-NOT [bool]$folderRemoved){
      Write-Warning "SCOM cache was not fully cleared; not all files/folders were deleted. For best results, try again or reboot and try again. Alternatively you could try clearing cache manually."
      Return $false
    }

    #default scenario, assumed something didn't go quite right
    Return $false
  }
}