SCCM Configmgr how to clean ccmcache content older than x days using compliance settings

A friend of mine asked for help on, how to clean up the content inside ccmcache folder in a better way instead of using a script to deploy it as application/package/task sequence to devices.

I would recommend using compliance settings(configuration item/configuration baseline) to deploy the script on a scheduled basis (monthly once or how you want) to Clients.

One advantage of using compliance settings is that you do not need to use source files to implement this solution and it would be easier to discover and remediate if any content found older than x days.

In this blog post, we will see, how to use simple PowerShell script (can get from many sources on the internet) to create configuration item and configuration baseline and deploy to clients.

If you do not want to follow all the steps outlined here, jump to the end of the post, to see how you can achieve this task in just 2 to 3 steps.

How to create Configuration Item:

launch SCCM console –>go to Assets and compliance—right click on Configuration Items—create Configuration Item

image

Give meaning full name something like clean ccmcache content

image

Leave the default settings and click next

image

Create new compliance rule

image

Follow the settings as outlined below .

You need to have 2 PowerShell scripts 1) Discovery to check the count of folders that are older than x days for deletion 2) To remediate (delete) these folders if any exist older than x days

image

For Discovery script ,click on edit script and use the following PowerShell script.

This script will tell us ,the count of folders inside the ccmcache older than X days which will help us to clean the content.

Change the number of days that you want to delete content older than.

#discovery script
$MinDays = 14
$UIResourceMgr = New-Object -ComObject UIResource.UIResourceMgr
$Cache = $UIResourceMgr.GetCacheInfo()
($Cache.GetCacheElements() |
where-object {[datetime]$_.LastReferenceTime -lt (get-date).adddays(-$mindays)} |
Measure-object).Count

For remediation script, use the following PowerShell script to clean the content older than 14 days:

This script will clean the content (folders) older than 14 days.

#remediate script
$MinDays = 14
$UIResourceMgr = New-Object -ComObject UIResource.UIResourceMgr
$Cache = $UIResourceMgr.GetCacheInfo()
$Cache.GetCacheElements() |
where-object {[datetime]$_.LastReferenceTime -lt (get-date).adddays(-$mindays)} |
foreach {
$Cache.DeleteCacheElement($_.CacheElementID)
}

click on compliance rules and click New

image

Enter the name that you wish to use for the rule name and select the return value by the discovery script 0.

The setting must comply rule used ,if the content returns by the discovery script is 0 ,there is no content to clean up ,if at all the discovery script return count value other than 0 then perform the content cleanup using the remediation script.

image

Click Ok, Ok and Next

image

verify once if the settings are configured correctly below.

image

Click next,next,next to see the summary page:

image

with this ,we have completed ,how to create Configuration Item which includes all the settings like discovery ,remediation .

How to create Configuration Baseline:

Right click on Configuration Baseline and select Create configuration Baseline

image

Give a Name,description and click on Add Configuration Item

image

Select the configuration item that we created above ,add and click ok .

image

we are now created configuration baseline and ready to deploy to collection that you are interested in with schedule.

How to deploy Configuration Baseline to Collection:

Right click on the configuration baseline that we created earlier and click on deploy

image

Adjust the below settings according to your environment like collection and schedule .

image

Under the deployment tab ,you will see the configuration baseline deployed to collection and its compliance %

image

Wait the clients to receive the policy (trigger machine policy retrieval ,if you want to speed up the process) and let remediation happen..

Go to any SCCM client ,open configuration manager applet, look at configurations tab ,you will there is no ccmcache cleanup available.

image

As soon as you refresh the machine policy ,client will poll and get the newly created policy which will appear in configurations tab ,click on evaluate.

image

Evaluate will take few seconds to run the discovery script and if it find the count other than 0 ,perform the remediation script that we used .

image

Click on view report to see a nice html report with compliance status

image

After a while ,client evaluate the baseline and report the status to SCCM ,which you can see in console ,configuration baseline.

image

With this ,we have completed task of how to clean up content in ccmcache older than 14 days.

How to avoid following these steps and create all in 3 steps ?

To make this task easier for you ,I have exported the Configuration baseline into cab file . So all you need is ,download the cab file from here ,go to configuration baseline ,import the cab file and change the settings how you want in the PowerShell using above steps.

Below are client the logs (C:\windows\ccm\logs) which will help you to check and troubleshoot compliance setting issues:

CIDownloader.log –>Records details about configuration item definition downloads.

DcmWmiProvider.log—>Records information about reading configuration item synclets from Windows Management Instrumentation (WMI).

DCMReporting.log—>Records information about reporting policy platform results into state messages for configuration items.

CIAgent.log—>Records details about the process of remediation and compliance for compliance settings, software updates, and application management.

46 Responses to "SCCM Configmgr how to clean ccmcache content older than x days using compliance settings"

  1. Hi Eswar,
    The below script do not delete old content from ccmcache folder for each machine, In some machines, it is working, whereas in some machines it is not working.
    #remediate script
    $MinDays = 14
    $UIResourceMgr = New-Object -ComObject UIResource.UIResourceMgr
    $Cache = $UIResourceMgr.GetCacheInfo()
    $Cache.GetCacheElements() |
    where-object {[datetime]$_.LastReferenceTime -lt (get-date).adddays(-$mindays)} |
    foreach {
    $Cache.DeleteCacheElement($_.CacheElementID)
    }

    Reply
  2. Andre van der Linden · Edit

    Hello,
    We have SCCM 2021 with hotfix (KB11121541) installed. And the cachesize in the client settings is 100GB, because we have a few big software installations. (60GB+) So the max size is on a lot of computer never reached. This is the reason I want to clean the cache every month.
    I created the baseline with succes, but I get a error on a lot of clients (timeout) how can I change the max. runtime?

    Reply
  3. Hi Eswar,
    Hi I have create the configuration baseline and pushed all system collection so the question is every user need to go in configuration manager and click on evaluate button ? or it will work automatically?

    Reply
    1. Hi Ravi,
      It does automatically based on the schedule that you have configured in the baseline policy.
      No user input needed.

      Thanks,
      Eswar

      Reply
  4. Could you please help me with the script to discover machine which has cache size = or grater than 5 GB.

    Want to create a automatic cache cleanup as mentioned Above.

    Reply
    1. Hi,
      With current branch, you really dont have to manage the client cache as you can configure the client settings for cache and does auto cleanup after x days.
      when the cache is almost getting full for the download of new content, the old content (based on the date) will automatically be removed.

      Thanks,
      Eswar

      Reply
            1. Hi Dante,
              Are you referring to client settings to install ps scripts? How is it not allowed? how are you blocking it?
              You can use scripts feature in configmgr to run it on the machine but it is going to one time.

              Thanks,
              Eswar

  5. Could someone help, please?
    I'm interested in modifying it to match the non-persistent settings that David mentions above.
    He says to modify the second line. Of which script?

    Assistance would be greatly appreciated, as it looks like implementing this as a baseline is going to really help us.

    Regards,
    Gerard

    Reply
    1. Hi,
      David query does not look for any period and simply delete all persistant content from cache folder.
      $ValidCacheItems = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Query 'SELECT ContentID,Location FROM CacheInfoEx WHERE PersistInCache != 1' -ErrorAction Stop | Select-Object -ExpandProperty ContentId
      David code looks like this (havent tested though just from mind):

      $ValidCacheItems = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Query 'SELECT ContentID,Location FROM CacheInfoEx WHERE PersistInCache != 1' -ErrorAction Stop | Select-Object -ExpandProperty ContentId|
      foreach {
      $Cache.DeleteCacheElement($_.CacheElementID)
      }
      $ValidCacheItems = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Query 'SELECT ContentID,Location FROM CacheInfoEx WHERE PersistInCache != 1' -ErrorAction Stop | Select-Object -ExpandProperty ContentId|
      foreach {
      $Cache.DeleteCacheElement($_.CacheElementID)
      }
      If you want to look for date with older than x days then must tweak the code accordingly.

      Thanks,
      Eswar

      Reply
  6. A colleague of mine change the second line to only get cached folders for non-persistent applications.

    $ValidCacheItems = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Query 'SELECT ContentID,Location FROM CacheInfoEx WHERE PersistInCache != 1' -ErrorAction Stop | Select-Object -ExpandProperty ContentId

    Reply
  7. Thanks a lot Eswar for the automated solution, policy start working after bypass powershell script execution in client agent settings.

    We have power-shell execution policy = AllSigned and we don't want to change the client settings, so is there any way without changing the client setting to make the script work ?

    Reply
    1. Using compliance Item ,you cannot deploy any scripts as file instead you can directly run script but for that ,you should have the setting enabled in client settings.
      If you have set to allsigned ,you can either create new client settings and choose bypass for this compliance item or create package to run on all machines every 2 weeks or so to cleanup the content. If you package/application method ,you can run the powershell script with bypass command line.

      Regards,
      Eswar

      Reply
      1. Hi Eswar,

        I have downloaded CAB file but i want to delete the content from CCMcache whihc is older than 45 days i don,t see any script that i need to update in.cab file .please help with the request

        Reply
        1. Hi Imran,
          After you import the cab file ,edit the configuration Item,go to settings ,edit the script (discovery script) ,change $MinDays = 7 to $MinDays = 45 or whatever you need,save changes.
          Do the same for remediation script as well ,save changes and you are done.

          Regards,
          Eswar

          Reply
          1. Hi Eswar,

            I have Implemented this and when we can see the compliance from SCCM i mean how long it will take to get the Compliance report.

            Reply
            1. what do you mean compliance report ? in CB report ? do you want to know whether CB is failure or success ? If so ,it will be right after the compliance baseline is executed.

              Regards,
              Eswar

            2. Have a look at the default reports to check the status . Did you run the default reports for compliance baseline ?

              Regards,
              Eswar

    1. Hi Kevin,
      thats interesting. I haven't tested with persistent option.you can give a try and post me the results if that works or not. Meantime i will check on this.

      Regards,
      Eswar

      Reply
    2. Hi Kevin,

      did you check this is it deleting Persistent cache as well? did you do any modification to maintain the persistent cache

      Reply
      1. I could not find persistent cache option in SCCM Current branch .Where do you see this option in the deployment ?

        Regards,
        Eswar

        Reply
  8. Thank you! I've been looking for a solution like this for a while now. Most of the laptops in my company have 128gb SSDs and those things full up pretty quick.

    Reply
    1. Hi Bruce,
      True, if you are running on SSD, disk fill up so easily due to applications and other stuff and it always need to clean old stuff.

      Regards,
      Eswar

      Thanks,
      Eswar

      Reply
      1. Hi Eswar,

        Some of the packages we create looks for Repair, as shorcuts are advertised. And we are facing many issues with the content missing from ccmcache folder. We used Persistent content option but do we have any alternative fix for this?

        Thanks.

        Reply
        1. Hi Mahesh,
          I will need to look at the script to exclude the content that are persisted. I will check on this weekend and update you.

          Regards,
          Eswar

          Reply

Post Comment