Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.88 KB | None | 0 0
  1. <#
  2. *********************************************************************************************************
  3. * *
  4. *** This Powershell Script is used to clean the CCM cache of all non persisted content ***
  5. * *
  6. *********************************************************************************************************
  7. * Created by Ioan Popovici, 13/11/2015 | Requirements Powershell 3.0 *
  8. * ======================================================================================================*
  9. * Modified by | Date | Revision | Comments *
  10. *_______________________________________________________________________________________________________*
  11. * Ioan Popovici | 13/11/2015 | v1.0 | First version *
  12. * Ioan Popovici | 16/11/2015 | v1.1 | Improved Logging *
  13. * Ioan Popovici | 16/11/2015 | v1.2 | Vastly Improved *
  14. * Ioan Popovici | 03/02/2016 | v2.0 | Vastly Improved *
  15. * Ioan Popovici | 04/02/2016 | v2.1 | Fixed TotalSize decimals *
  16. *-------------------------------------------------------------------------------------------------------*
  17. * *
  18. *********************************************************************************************************
  19.  
  20. .SYNOPSIS
  21. This Powershell Script is used to clean the CCM cache of all non persisted content.
  22. .DESCRIPTION
  23. This Powershell Script is used to clean the CCM cache of all non persisted content that is not needed anymore.
  24. It only cleans packages, applications and updates that have a installed status and are not persisted, othercache items
  25. will NOT be cleaned.
  26. #>
  27.  
  28. ##*=============================================
  29. ##* INITIALIZATION
  30. ##*=============================================
  31. #region Initialization
  32.  
  33. ## Cleaning prompt history
  34. CLS
  35.  
  36. ## Global variable
  37. $Global:Result =@()
  38.  
  39. ## Initalize progress Counter
  40. $ProgressCounter = 0
  41.  
  42. ## Configure Logging
  43. # Set log path
  44. $ResultCSV = "C:\Temp\Clean-CCMCache.log"
  45.  
  46. # Remove previous log it it's more than 500 KB
  47. If (Test-Path $ResultCSV) {
  48. If ((Get-Item $ResultCSV).Length -gt 500KB) {
  49. Remove-Item $ResultCSV -Force | Out-Null
  50. }
  51. }
  52.  
  53. # Get log parent path
  54. $ResultPath = Split-Path $ResultCSV -Parent
  55.  
  56. # Create path directory if it does not exist
  57. If ((Test-Path $ResultPath) -eq $False) {
  58. New-Item -Path $ResultPath -Type Directory | Out-Null
  59. }
  60.  
  61. ## Get the current date
  62. $Date = Get-Date
  63.  
  64. ## Get list of all non persisted content in CCMCache, only this content will be removed
  65. $CM_CacheItems = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Query 'SELECT ContentID,Location FROM CacheInfoEx WHERE PersistInCache = 0'
  66.  
  67.  
  68. #endregion
  69. ##*=============================================
  70. ##* END INITIALIZATION
  71. ##*=============================================
  72.  
  73. ##*=============================================
  74. ##* FUNCTION LISTINGS
  75. ##*=============================================
  76. #region FunctionListings
  77.  
  78. #region Function Remove-CacheItem
  79. Function Remove-CacheItem {
  80. <#
  81. .SYNOPSIS
  82. Removes SCCM cache item if it's not persisted.
  83. .DESCRIPTION
  84. Removes specified SCCM cache item if it's not found in the persisted cache list.
  85. .PARAMETER CacheItemToDelete
  86. The cache item ID that needs to be deleted.
  87. .PARAMETER CacheItemName
  88. The cache item name that needs to be deleted.
  89. .EXAMPLE
  90. Remove-CacheItem -CacheItemToDelete "{234234234}" -CacheItemName "Office2003"
  91. .NOTES
  92. .LINK
  93. #>
  94. [CmdletBinding()]
  95. Param (
  96. [Parameter(Mandatory=$true,Position=0)]
  97. [Alias('CacheTD')]
  98. [string]$CacheItemToDelete,
  99. [Parameter(Mandatory=$true,Position=1)]
  100. [Alias('CacheN')]
  101. [string]$CacheItemName
  102. )
  103.  
  104. ## Delete chache item if it's non persisted
  105. If ($CM_CacheItems.ContentID -contains $CacheItemToDelete) {
  106.  
  107. # Get Cache item location and size
  108. $CacheItemLocation = $CM_CacheItems | Where {$_.ContentID -Contains $CacheItemToDelete} | Select -ExpandProperty Location
  109. $CacheItemSize = Get-ChildItem $CacheItemLocation -Recurse -Force | Measure-Object -Property Length -Sum | Select -ExpandProperty Sum
  110.  
  111. # Build result object
  112. $ResultProps = [ordered]@{
  113. 'DeletionDate' = $Date
  114. 'Name' = $CacheItemName
  115. 'ID' = $CacheItemToDelete
  116. 'Location' = $CacheItemLocation
  117. 'Size(MB)' = "{0:N2}" -f ($CacheItemSize / 1MB)
  118. 'TotalDeleted(MB)' = ''
  119. }
  120.  
  121. # Add items to result object
  122. $Global:Result += New-Object PSObject -Property $ResultProps
  123.  
  124. # Connect to resource manager COM object
  125. $CMObject = New-Object -ComObject "UIResource.UIResourceMgr"
  126.  
  127. # Use GetCacheInfo method to return cache properties
  128. $CMCacheObjects = $CMObject.GetCacheInfo()
  129.  
  130. # Delete Cache element
  131. $CMCacheObjects.GetCacheElements() | Where-Object {$_.ContentID -eq $CacheItemToDelete} |
  132. ForEach-Object {
  133. $CMCacheObjects.DeleteCacheElement($_.CacheElementID)
  134. }
  135. }
  136. }
  137. #endregion
  138.  
  139. #region Function Remove-CachedApplications
  140. Function Remove-CachedApplications {
  141. <#
  142. .SYNOPSIS
  143. Removes SCCM cached application.
  144. .DESCRIPTION
  145. Removes specified SCCM cache application if it's already installed.
  146. .PARAMETER
  147. .EXAMPLE
  148. .NOTES
  149. .LINK
  150. #>
  151.  
  152. ## Get list of applications
  153. $CM_Applications = Get-WmiObject -Namespace root\ccm\ClientSDK -Query 'SELECT * FROM CCM_Application'
  154.  
  155. ## Check for installed applications
  156. Foreach ($Application in $CM_Applications) {
  157.  
  158. ## Show progrss bar
  159. If ($CM_Applications.Count -ne $null) {
  160. $ProgressCounter++
  161. Write-Progress -Activity 'Processing Applications' -CurrentOperation $Application.FullName -PercentComplete (($ProgressCounter / $CM_Applications.Count) * 100)
  162. Start-Sleep -Milliseconds 400
  163. }
  164. ## Get Application Properties
  165. $Application.Get()
  166.  
  167. ## Enumerate all deployment types for an application
  168. Foreach ($DeploymentType in $Application.AppDTs) {
  169. If ($Application.InstallState -eq "Installed" -and $Application.IsMachineTarget) {
  170.  
  171. ## Get content ID for specific application deployment type
  172. $AppType = "Install",$DeploymentType.Id,$DeploymentType.Revision
  173. $Content = Invoke-WmiMethod -Namespace root\ccm\cimodels -Class CCM_AppDeliveryType -Name GetContentInfo -ArgumentList $AppType
  174.  
  175. ## Call Remove-CacheItem function
  176. Remove-CacheItem -CacheTD $Content.ContentID -CacheN $Application.FullName
  177. }
  178. }
  179. }
  180. }
  181. #endregion
  182.  
  183. #region Function Remove-CachedPackages
  184. Function Remove-CachedPackages {
  185. <#
  186. .SYNOPSIS
  187. Removes SCCM cached package.
  188. .DESCRIPTION
  189. Removes specified SCCM cached package if it's not needed anymore.
  190. .PARAMETER
  191. .EXAMPLE
  192. .NOTES
  193. .LINK
  194. #>
  195.  
  196. ## Get list of packages
  197. $CM_Packages = Get-WmiObject -Namespace root\ccm\ClientSDK -Query 'SELECT PackageID,PackageName,LastRunStatus,RepeatRunBehavior FROM CCM_Program'
  198.  
  199. ## Check if any deployed programs in the package need the cached package and add deletion or exemption list for comparison
  200. ForEach ($Program in $CM_Packages) {
  201.  
  202. # Check if program in the package needs the cached package
  203. If ($Program.LastRunStatus -eq "Succeeded" -and $Program.RepeatRunBehavior -ne "RerunAlways" -and $Program.RepeatRunBehavior -ne "RerunIfSuccess") {
  204.  
  205. # Add PackageID to Deletion List if not already added
  206. If ($Program.PackageID -NotIn $PackageIDDeleteTrue) {
  207. [array]$PackageIDDeleteTrue += $Program.PackageID
  208. }
  209.  
  210. } Else {
  211.  
  212. # Add PackageID to Exception List if not already added
  213. If ($Program.PackageID -NotIn $PackageIDDeleteFalse) {
  214. [array]$PackageIDDeleteFalse += $Program.PackageID
  215. }
  216. }
  217. }
  218.  
  219. ## Parse Deletion List and Remove Package if not in Exemption List
  220. ForEach ($Package in $PackageIDDeleteTrue) {
  221.  
  222. # Show progress bar
  223. If ($CM_Packages.Count -ne $null) {
  224. $ProgressCounter++
  225. Write-Progress -Activity 'Processing Packages' -CurrentOperation $Package.PackageName -PercentComplete (($ProgressCounter / $CM_Packages.Count) * 100)
  226. Start-Sleep -Milliseconds 800
  227. }
  228. # Call Remove Function if Package is not in $PackageIDDeleteFalse
  229. If ($Package -NotIn $PackageIDDeleteFalse) {
  230. Remove-CacheItem -CacheTD $Package.PackageID -CacheN $Package.PackageName
  231. }
  232. }
  233. }
  234. #endregion
  235.  
  236. #region Function Remove-CachedUpdates
  237. Function Remove-CachedUpdates {
  238. <#
  239. .SYNOPSIS
  240. Removes SCCM cached updates.
  241. .DESCRIPTION
  242. Removes specified SCCM cached update if it's not needed anymore.
  243. .PARAMETER
  244. .EXAMPLE
  245. .NOTES
  246. .LINK
  247. #>
  248.  
  249. ## Get list of updates
  250. $CM_Updates = Get-WmiObject -Namespace root\ccm\SoftwareUpdates\UpdatesStore -Query 'SELECT UniqueID,Title,Status FROM CCM_UpdateStatus'
  251.  
  252. ## Check if cached updates are not needed and delete them
  253. ForEach ($Update in $CM_Updates) {
  254.  
  255. # Show Progrss bar
  256. If ($CM_Updates.Count -ne $null) {
  257. $ProgressCounter++
  258. Write-Progress -Activity 'Processing Updates' -CurrentOperation $Update.Title -PercentComplete (($ProgressCounter / $CM_Updates.Count) * 100)
  259. }
  260.  
  261. # Check if update is already installed
  262. If ($Update.Status -eq "Installed") {
  263.  
  264. # Call Remove-CacheItem function
  265. Remove-CacheItem -CacheTD $Update.UniqueID -CacheN $Update.Title
  266. }
  267. }
  268. }
  269. #endregion
  270.  
  271. #endregion
  272. ##*=============================================
  273. ##* END FUNCTION LISTINGS
  274. ##*=============================================
  275.  
  276. ##*=============================================
  277. ##* SCRIPT BODY
  278. ##*=============================================
  279. #region ScriptBody
  280.  
  281. ## Call Remove-CachedApplications function
  282. Remove-CachedApplications
  283.  
  284. ## Call Remove-CachedApplications function
  285. Remove-CachedPackages
  286.  
  287. ## Call Remove-CachedApplications function
  288. Remove-CachedUpdates
  289.  
  290. ## Get Result sort it and build Result Object
  291. $Result = $Global:Result | Sort-Object Size`(MB`) -Descending
  292.  
  293. # Calculate total deleted size
  294. $TotalDeletedSize = $Result | Measure-Object -Property Size`(MB`) -Sum | Select -ExpandProperty Sum
  295.  
  296. # If $TotalDeletedSize is zero write that nothing could be deleted
  297. If ($TotalDeletedSize -eq $null) {
  298. $TotalDeletedSize = "Nothing to Delete!"
  299. }
  300.  
  301. # Build Result Object
  302. $ResultProps = [ordered]@{
  303. 'DeletionDate' = $Date
  304. 'Name' = 'Total Size of Items Deleted in MB:'
  305. 'ID' = ''
  306. 'Location' = ''
  307. 'Size(MB)' = ''
  308. 'TotalDeleted(MB)' = '{0:N2}' -f $TotalDeletedSize
  309. }
  310.  
  311. # Add total items deleted to result object
  312. $Result += New-Object PSObject -Property $ResultProps
  313.  
  314. ## Write Result Object to csv file (append)
  315. $Result | Export-Csv -Path $ResultCSV -Delimiter ";" -Encoding UTF8 -NoTypeInformation -Append -Force
  316.  
  317. ## Write Result to console
  318. $Result | Format-Table Name,TotalDeleted`(MB`)
  319.  
  320. ## Let the user know we are finished
  321. Write-Host ""
  322. Write-Host "Processing Finished!" -BackgroundColor Green -ForegroundColor White
  323.  
  324. #endregion
  325. ##*=============================================
  326. ##* END SCRIPT BODY
  327. ##*=============================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement