Powershell – Delete files older than x days

 
###FUNCTION TO DELETE OLD FILES
function deleteOldFiles
(
[int]$numberOfDays = $(throw "Specify the number of days")
)
{
$Now = Get-Date
$TargetFolder = “C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup”
$LastWrite = $Now.AddDays(-$numberOfDays)
$Files = get-childitem $TargetFolder -include *.bak, *.x86 -recurse | Where {$_.LastWriteTime -le “$LastWrite”}

foreach ($File in $Files)
{
write-host “Deleting File $File” -foregroundcolor “Red”;
Remove-Item $File | out-null
}
}


deleteOldFiles(3)

2 thoughts on “Powershell – Delete files older than x days

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: