Advertisement
Guest User

SCCM Contentlibrarycleanup tool Powershell

a guest
Jun 23rd, 2025
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 5.23 KB | Source Code | 0 0
  1. [parameter(Mandatory = $true, HelpMessage = "Value added to the log file.")]
  2.  
  3. [ValidateNotNullOrEmpty()] [string]$Value,
  4.  
  5. [parameter(Mandatory = $true, HelpMessage = "Severity for the log entry. 1 for Informational, 2 for Warning and 3 for Error.")]
  6.  
  7. [ValidateNotNullOrEmpty()] [ValidateSet("1", "2", "3")] [string]$Severity,
  8.  
  9. [parameter(Mandatory = $false, HelpMessage = "Name of the log file that the entry will written to.")]
  10.  
  11. [ValidateNotNullOrEmpty()] [string]$FileName = "ScheduledContentLibraryCleanup-$(Get-Date -Format dd-MM-yyyy).log" )
  12. # Determine log file location
  13. $LogFilePath = Join-Path -Path $ScriptDirectory -ChildPath $FileName
  14. # Construct time stamp for log entry
  15. $Time = -join @((Get-Date -Format "HH:mm:ss.fff"), "+", (Get-WmiObject -Class Win32_TimeZone | Select-Object -ExpandProperty Bias))
  16. # Construct date for log entry
  17. $Date = (Get-Date -Format "MM-dd-yyyy")
  18. # Construct context for log entry
  19. $Context = $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
  20. # Construct final log entry
  21. $LogText = "<![LOG[$($Value)]LOG]!><time=""$($Time)"" date=""$($Date)"" component=""ScheduledContentLibraryCleanup"" context=""$($Context)"" type=""$($Severity)"" thread=""$($PID)"" file="""">"
  22. # Add value to log file
  23. try { Add-Content -Value $LogText -LiteralPath $LogFilePath -ErrorAction Stop } catch [System.Exception] { Write-Warning -Message "Unable to append log entry to ScheduledContentLibraryCleanup.log file. Error message: $($_.Exception.Message)" } }
  24.  
  25. # Import SCCM PowerShell Module $ModuleName = (Get-Item $env:SMS_ADMIN_UI_PATH).parent.FullName + "\ConfigurationManager.psd1" Write-CMLogEntry -Value "RUNNING: ConfigMgr PS commandlets path set to $ModuleName" -Severity 1
  26. # Specify SCCM Site Vairables
  27. $SiteServer = %SITESERVER% Write-CMLogEntry -Value "RUNNING: Site server identified as $SiteServer" -Severity 1
  28. $SiteCode = %SITECODE% Write-CMLogEntry -Value "RUNNING: SMS site code identified as $SiteCode" -Severity 1
  29. # Define Content Library Path Location
  30. $ContentLibraryExe = ("$($env:SMS_LOG_PATH | Split-Path -Parent)" + "\cd.latest\SMSSETUP\TOOLS\ContentLibraryCleanup\ContentLibraryCleanup.exe")
  31. # Define Arrays
  32. $DistributionPoints = New-Object -TypeName System.Collections.ArrayList
  33. # Import SCCM Module
  34. Import-Module $ModuleName
  35. # Connect to Site Code PS Drive
  36. Set-Location -Path ($SiteCode + ":")
  37. # List Distribution Points
  38. $DistributionPoints = @(((Get-CMDistributionPoint | Select-Object NetworkOSPath).NetworkOSPath).TrimStart("\\"))
  39. # Specify Temp Log Location
  40. $LogDir = ($ScriptDirectory + "\ContentLibraryCleanerLogs")
  41.  
  42. function CleanContent { param (
  43.  
  44. [parameter(Mandatory = $true)]
  45.  
  46. [String]$DistributionPoint,
  47.  
  48. [parameter(Mandatory = $true)]
  49.  
  50. [String]$SiteServer,
  51.  
  52. [parameter(Mandatory = $true)]
  53.  
  54. [String]$SiteCode ) try { Write-CMLogEntry -Value "CLEANING: Setting location to $ScriptDirectory" -Severity 1 Set-Location -Path $ScriptDirectory
  55.  
  56. # Content Library Cleanup switches
  57. Write-CMLogEntry -Value "CLEANING: Setting execution switches to $ContentCleanupString" -Severity 1
  58. $ContentCleanupStrings = "/q /ps $SiteServer /dp $DistributionPoint /sc $SiteCode /delete"
  59. Write-Host "Running process for $DistributionPoint"
  60. Write-CMLogEntry -Value "CLEANING: Starting clean up process for server $DistributionPoint" -Severity 1
  61. $RunningProcess = Start-Process -FilePath $ContentLibraryExe -ArgumentList $ContentCleanupStrings -NoNewWindow -RedirectStandardOutput $($LogDir + "\$DistributionPoint-ScheduledDeletionJob.log") -PassThru
  62.  
  63. # Wait for Process completion
  64. While ((Get-Process | Where-Object { $_.Id -eq $RunningProcess.Id }).Id -ne $null) { Write-CMLogEntry -Value "CLEANING: Waiting for process PID:$($RunningProcess.Id) to finish" -Severity 1 sleep -Seconds 1 }
  65.  
  66. # Get most recent log file generated
  67. $ContentCleanUpLog = Get-ChildItem -Path $LogDir -Filter *.log | Where-Object { ($_.Name -match "$DistributionPoint-ScheduledDeletionJob") } | select -First 1
  68.  
  69. # Exception for reports with active distributions preventing the content rule from estimating space
  70. if ((Get-Content -Path $ContentCleanUpLog.FullName | Where-Object { $_ -match "This content library cannot be cleaned up right now" }) -ne $null) { Write-CMLogEntry -Value "CLEANING: $DistributionPoint currently has active transfers. Skipping." -Severity 2 $RowData = @($DistributionPoint, "N/A – Active Transfers")
  71. }
  72. else
  73. { Write-CMLogEntry -Value "CLEANING: Process completed" -Severity 1 }} catch [System.Exception] { Write-CMLogEntry -Value "ERROR: $($_.Exception.Message)" -Severity 3 Write-Warning -Message "ERROR: $($_.Exception.Message)" } Write-CMLogEntry -Value "Finished: Job Complete" -Severity 1 }
  74. foreach ($DistributionPoint in $DistributionPoints) { Write-CMLogEntry -Value "RUNNING: Starting clean up process for server $DistributionPoint" -Severity 1 CleanContent $DistributionPoint $SiteServer $SiteCode }
  75.  
  76. # // ————- Clean Up Log Files ———– // #
  77.  
  78. # Define Maximum Log File Age
  79. $MaxLogAge = 30
  80.  
  81. # Remove Logs
  82. Write-CMLogEntry -Value "CLEANING: Removing log files older than $MaxLogAge days old" -Severity 2
  83. Get-ChildItem -Path $ScriptDirectory -Filter "ScheduledContentLibrary*.log" -File | Where-Object {$_.LastWriteTime -lt ((Get-Date).AddDays(-$MaxLogAge))} | Remove-Item
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement