I have a script that deletes anything older than a set time. I want to replicate this for other delete jobs with different times and different folders
I am new to Powershell, this script was written with a lot of google assistance
$Minutes=[DateTime]::Now.AddMinutes(-5)
$Timestamp = Get-Date -Format "yyyy-MM-ddTHH-mm-ss"
$Log = "C:\test\logs\_" + $Timestamp + ".log"
Start-Transcript -path $Log -append -Force -NoClobber
try {
function Write-Log($string)
{
$outStr = "" + $Timestamp +" "+$string
Write-Output $outStr
}
Write-Log "------------ Start of Log ------------"
#Write-Log ""
# get all file objects to use in erasing
$files=Get-ChildItem -path 'c:\test\*' -Include *.* -Recurse |
Where-Object{ $_.LastWriteTime -lt $Minutes}
# Remove the file and its folder.
$files |
ForEach-Object{
Write-Log " Deleting File --> $_."; Remove-Item $_.Fullname
}
# output statistics
Write-Output "**********************"
Write-Output "Number of old files deleted: $($files.Count)"
Write-Log "------------- End of Log -------------"
}
catch {
Write-Error -Message "Something bad happened!" -ErrorAction Stop
}
Stop-Transcript