Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion scripts_staging/TasksUpdater/Updater P3 Run Cleaner.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,18 @@
Logging snippet for logging
Updater P3.5 Schedules parser snippet for parsing the date
Cleaner & VHDXCleaner snippet to run the actual cleans
Ps7 snippnet
#public


.CHANGELOG
28.11.24 SAN Incorporated VHDX cleaner.
13.12.24 SAN Split logging from parser.
#>
06.08.25 SAN upgrade to ps7

#>

{{CallPowerShell7}}

# Name will be used for both the name of the log file and what line of the Schedules to parse
$PartName = "TempFileCleanup"
Expand Down
105 changes: 48 additions & 57 deletions scripts_staging/snippets/Cleaner.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
19.11.24 SAN added cleanup of search index
17.12.24 SAN Full code refactoring, set a single value for file expiration
14.01.25 SAN More verbose output for the deletion of items
11.08.25 SAN Run cleanmgr in the background
18.08.25 SAN fix disk info error, missing function, sccm condition and made it move verbose.
10.09.25 SAN added output for to check if cleanmgr is running

.TODO
Integrate bleachbit this would help avoid having to update this script too often.
Expand All @@ -35,70 +38,39 @@ $DaysToDelete = if ([string]::IsNullOrEmpty($env:DaysToDelete)) { 30 } else { [i

Write-Host "Days to delete set to: $DaysToDelete"

$VerbosePreference = "Continue"
$ErrorActionPreference = "SilentlyContinue"

$Starters = Get-Date

# Function to retrieve and display disk space info
function Get-DiskInfo {
$DiskInfo = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 } |
Select-Object SystemName,
@{ Name = "Drive"; Expression = { $_.DeviceID } },
@{ Name = "Size (GB)"; Expression = { "{0:N1}" -f ($_.Size / 1GB) } },
@{ Name = "FreeSpace (GB)"; Expression = { "{0:N1}" -f ($_.FreeSpace / 1GB) } },
@{ Name = "PercentFree"; Expression = { "{0:P1}" -f ($_.FreeSpace / $_.Size) } }
return $DiskInfo
try {
$DiskInfo = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 } # 3 = Local Disk
foreach ($disk in $DiskInfo) {
[PSCustomObject]@{
DeviceID = $disk.DeviceID
VolumeName = $disk.VolumeName
FileSystem = $disk.FileSystem
FreeSpaceGB = [math]::Round($disk.FreeSpace / 1GB, 2)
SizeGB = [math]::Round($disk.Size / 1GB, 2)
}
}
} catch {
Write-Host "[ERROR] Failed to retrieve disk information. $_"
}
}

function Remove-Items {
param (
param(
[string]$Path,
[int]$Days
)

if (Test-Path $Path) {
# Check if the Path is a file
if ((Get-Item $Path).PSIsContainer -eq $false) {
try {
# Remove the single file if it meets the age condition
if ((Get-Item $Path).CreationTime -lt (Get-Date).AddDays(-$Days)) {
Remove-Item -Path $Path -Force -Verbose -Confirm:$false
Write-Host "[DONE] Removed single item: $Path"
} else {
Write-Host "[INFO] $Path does not meet the age condition, skipping removal."
}
} catch {
Write-Host "[ERROR] Failed to remove item: $Path. $_"
}
} else {
try {
# Get all items in the folder
$items = Get-ChildItem -Path $Path -Recurse -Force |
Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-$Days) } |
Sort-Object { $_.Name.Length } -Descending

if ($items.Count -gt 0) {
Write-Host "[INFO] Listing items for removal in order of name length:"
foreach ($item in $items) {
Write-Host " - $($item.FullName)"
}

# Remove items from longest name to shortest
$items | Remove-Item -Force -Recurse -Verbose -Confirm:$false
Write-Host "[DONE] Cleaned up directory: $Path"
} else {
Write-Host "[INFO] No items met the age condition in directory: $Path"
}
} catch {
Write-Host "[ERROR] Failed to clean up directory: $Path. $_"
}
}
} else {
Write-Host "[WARNING] $Path does not exist, skipping cleanup."
Get-ChildItem -Path $Path -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-$Days) } |
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}
}


# Function to add or update registry keys for Disk Cleanup
function Add-RegistryKeys-CleanMGR {
$baseKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
Expand Down Expand Up @@ -157,13 +129,19 @@ $Before = Get-DiskInfo | Format-Table -AutoSize | Out-String
Stop-Service -Name wuauserv -Force -ErrorAction SilentlyContinue -Verbose

# Adjust SCCM cache size if configured
$cache = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Class CacheConfig
if ($cache) {
$cache.size = 1024
$cache.Put() | Out-Null
Restart-Service ccmexec -ErrorAction SilentlyContinue
try {
$cache = Get-WmiObject -Namespace root\ccm\SoftMgmtAgent -Class CacheConfig -ErrorAction Stop
if ($cache) {
$cache.size = 1024
$cache.Put() | Out-Null
Restart-Service ccmexec -ErrorAction SilentlyContinue
Write-Host "[INFO] SCCM cache size adjusted and ccmexec service restarted."
}
} catch {
Write-Host "[INFO] SCCM client not detected. Skipping cache configuration."
}


# Compaction of Windows.edb
$windowsEdbPath = "$env:ALLUSERSPROFILE\\Microsoft\\Search\\Data\\Applications\\Windows\\Windows.edb"
if (Test-Path $windowsEdbPath) {
Expand Down Expand Up @@ -205,9 +183,22 @@ foreach ($Path in $UserPathsToClean.Values) {

# Add registry keys for Disk Cleanup
Add-RegistryKeys-CleanMGR

# Run Disk Cleanup with custom settings
Start-Process -FilePath "cleanmgr.exe" -ArgumentList "/sagerun:1" -Wait
$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = "cleanmgr.exe"
$processStartInfo.Arguments = "/sagerun:1"
$processStartInfo.UseShellExecute = $true # Allows the executable to run independently
$processStartInfo.CreateNoWindow = $true # Prevents a new window from being created
# Start the process (no wait)
[System.Diagnostics.Process]::Start($processStartInfo) | Out-Null
Start-Sleep -Seconds 5
$process = Get-Process -Name "cleanmgr" -ErrorAction SilentlyContinue
if ($null -ne $process) {
Write-Output "[DONE] Disk Cleanup is running."
} else {
Write-Output "[ERR] Disk Cleanup is NOT running."
}


# Gather disk usage after cleanup
$After = Get-DiskInfo | Format-Table -AutoSize | Out-String
Expand Down