Script Example: MSH Delete Files Older Than 30 Days
Keeping a system tidy often means removing old files that are no longer needed. Below is a concise, practical script example using Windows PowerShell (MSH) to find and delete files older than 30 days. The script is safe-by-default, includes logging, and offers a dry-run option so you can verify results before deleting anything.
What this script does
- Scans a target directory (and its subfolders) for files older than 30 days.
- Logs matched files to a timestamped log file.
- Supports a dry-run mode to list files without deleting.
- Optionally deletes matched files when run without dry-run.
Script (PowerShell)
powershell
# Parameters - change as needed \(TargetPath = "C:\Path\To\Target\Folder" \)DaysOld = 30 \(DryRun = \)true# Set to \(false to actually delete \)LogFolder = “$env:USERPROFILE\Desktop\MSH_DeleteLogs”Prepare
if (-not (Test-Path -Path $LogFolder)) {
New-Item -ItemType Directory -Path $LogFolder -Force | Out-Null} \(Timestamp = (Get-Date).ToString("yyyyMMdd_HHmmss") \)LogFile = Join-Path \(LogFolder "DeleteFiles_OlderThan\){DaysOld}_$Timestamp.log”
Find files older than threshold
\(Cutoff = (Get-Date).AddDays(-\)DaysOld) \(Files = Get-ChildItem -Path \)TargetPath -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -lt $Cutoff }Log header
“Script run: \((Get-Date)" | Out-File -FilePath \)LogFile -Encoding UTF8 “Target Path: \(TargetPath" | Out-File -FilePath \)LogFile -Append “Days older than: \(DaysOld" | Out-File -FilePath \)LogFile -Append “Dry run: \(DryRun" | Out-File -FilePath \)LogFile -Append “” | Out-File -FilePath $LogFile -Append
if ($Files.Count -eq 0) {
"No files found older than $DaysOld days." | Out-File -FilePath $LogFile -Append Write-Output "No files found older than $DaysOld days." return}
List matches
“Found \((\)Files.Count) file(s):” | Out-File -FilePath \(LogFile -Append \)Files | ForEach-Object {
"$($_.FullName) | LastWriteTime: $($_.LastWriteTime)" | Out-File -FilePath $LogFile -Append}
if ($DryRun) {
Write-Output "Dry run enabled. No files were deleted. See log: $LogFile" return}
Delete files
foreach (\(f in \)Files) {
try { Remove-Item -LiteralPath $f.FullName -Force -ErrorAction Stop "DELETED: $($f.FullName)" | Out-File -FilePath $LogFile -Append } catch { "ERROR deleting $($f.FullName): $($_.Exception.Message)" | Out-File -FilePath $LogFile -Append }}
Write-Output “Deletion complete. See log: \(LogFile" </code></div></div></pre> <h3>Usage notes and safety tips</h3> <ul> <li><strong>Dry run first:</strong> Keep \)DryRun = $true until you confirm the listed files are safe to remove.
Backups: Ensure important data is backed up before running bulk delete operations. Target path: Use explicit absolute paths to avoid accidental deletion in the wrong directory. Permissions: Comments
Leave a Reply