Delete old files using powershell script

Powershell script to delete old backup files


# Change.1 - Update how old files needs to be deleted 
$oldTime = [int] 26 # 26 hours
#change.2: Update the path where files needs to be deleted
$PathList = "C:\del" ,"C:\del\del2"

foreach ($path in $PathList) {
	Write-Host "Deleting files older than $oldTime hours, in $path" -ForegroundColor Green
#Change.3 Update the include files to guide which type of files to be deleted. Remove the clause to delete all files
#change.4 Remove Archive criteria if it is not applicable.
	Get-ChildItem $path -Recurse -Include "*.txt", "*.out", "*.bacpac" | where {($_.attributes -notmatch "Archive") -and ($_.CreationTime -le $(Get-Date).AddHours(-$oldTime))} | Remove-Item -Force

}



# NOTE: in SQL Server, I have removed comments and made few modifications to address escape character failures.

$oldTime = [int]26
$mydate=Get-Date
foreach ($path in Get-Content "M:\Path\pathList.txt") {
	Get-ChildItem $path -Recurse -Include "*.LSBAK", "*.LSTRN" | where {($_.attributes -notmatch "Archive") -and ($_.CreationTime -le $mydate.AddHours(-$oldTime))} | Remove-Item -Force
}

#
Advertisements
This entry was posted in Powershell, Productivity, Uncategorized and tagged , , , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s