Using PowerShell – Remove Old Files


PowerShell is a powerful scripting shell that lets administrators and developers automate server administration and application deployment. The PowerShell language supports more complex logic than Transact-SQL scripts, giving SQL Server administrators the ability to build robust administration scripts.

One of the routine example is purge Old files. Administrator needs to remove the old files from the disk or archive older files to some location. We can do this by writing vb script, c# script; PowerShell even by SQL Server Maintenance plans as well. But here I am going to demonstrate the same using PowerShell script in just few lines.

$Now = Get-Date$Days = “5”

$LastWrite = $Now.AddDays(-$days)

$TargetFolder = “\\server\folder\”

$Files = get-childitem $TargetFolder | Where {$_.LastWriteTime -le “$LastWrite”}

foreach ($File in $Files)

{write-host “Deleting File $TargetFolder$File” -foregroundcolor “Red”; Remove-Item $TargetFolder$File}

The above script helps to delete the files older than 5 days.

How to use it :

  • Save the script using extension .ps1 E.g. CleanupFile.ps1
  • Run the script using command prompt or you can run it directly from powershell command prompt.

powershell C:\CleanupFile.ps1

Enjoy Scripting!

Advertisements

2 thoughts on “Using PowerShell – Remove Old Files

  1. Pingback: Using Powershell – Backup Database « SQL Server Blog

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