I am working on a script that basically looks for a folder name and then recurses through the folder structure finding files with a specific extension and then delete those files older than X amount of days, then output the results into a CSV file.
# *IMPORTANT* DOUBLE CHECK
$fileType = '*.dwg'
$foldername = "Site Plans"
# *IMPORTANT* DOUBLE CHECK - Get the current date and calculate the date -XX days ago
$currentDate = Get-Date
$cutOffDate = $currentDate.AddDays(-1)
### START SCRIPT ###
#$path = "C:\Users\zbarchuk\desktop\Site Plans - Copy"
$path = Get-ChildItem -Path C:\ | Where-Object {$_.Name -eq $foldername}
# Get Top Folder Name from path
#$pathTopFolder = ($path).split("\")[-1]
# $PSScriptRoot is the current path to the script ****
$GetDate = Get-Date -Format "MM-dd-yyyy_HH_mm_ss"
# File Stats
$log = [System.Collections.ArrayList]@("FileName, FilePath, FileSize")
$TotalSize = 0
# Get all files with the .pdf extension that are older than 45 days in all directories and subdirectories
$filesToDelete = Get-ChildItem -Path $path -Recurse -Filter $fileType | Where-Object { $_.LastWriteTime -lt $cutOffDate }
# Get File Item Count
$count = 1
$fileCount = @($filesToDelete).Count
# Delete each file
$OutputLog = @()
foreach ($file in $filesToDelete) {
#Get Item Size and add to file array
$size=[math]::Round((Get-Item -LiteralPath $file.FullName).length/1MB,2)
Write-Progress -Activity $count"/"$fileCount
#Write-Host -Activity "Deleting " $file.FullName
#Calc total size of deleted files
$TotalSize = ($TotalSize + $size)
#Remove-Item $file.FullName -Force
$count = $count+1
$OutputLog+=@([PSCustomObject]@{
FileName = $file
FilePath = Split-Path -Parent ($file.FullName)
FileSize = "$size" + " MB"
})
}
$OutputLog+=@([PSCustomObject]@{
FileName = "Total PDF File Cleanup Size"
FilePath = "Total Items=$fileCount"
FileSize = "$TotalSize MB"
})
$OutputLog | Export-CSv -Path C:\users\zbarchuk\desktop\CleanupOutputLog.csv
The issue I am running into and can't seem to figure out is the $path Get-ChildItem code is grabbing all folders with a similar name to the one I am looking for. I have tried various iterations using -Unique -Eq -Match but nothing seems to set it to only look for that specific folder name. Any help would be greatly appreciated!
This code takes into account that there could be multiple
Site Plansdirectories. It also omits the summary totals in favor of doing it from the log file after completion.The
Remove-Itemcommand is used, but it has-WhatIfwhich will cause it to only report what it would do. This allows you to safely run the script many times without deleting any files.After producing the log file, generate the count and size with:
or