File manipulation with Powershell

Some time ago I had a need to move some regularly generated files on a nightly basis off a disk due to storage concerns while a long term solution( a new SAN) was installed. In addition to moving them I only needed to keep them for 14 days, the best way of managing both these tasks is with powershell.

Moving the Files

Moving the files is quite simple, it is literally Move-Item . You can specify extensions by using *.extension and in that way narrow the files that are moved.

#region Copying the databases to the remote location

Move-Item d:\test\*.bak Y:\test
Move-Item e:\test\*.trn Y:\test1
Move-Item d:\test\*.txt Y:\test2

#Endregion

Cleaning up files older than 14 days

As the files are not required to be retained for longer than 14 days it is best to keep the clutter down and its a simple matter to extend the above copy script to clean up after itself.

The best way of doing this is to get the current date and then Add -14 to the current date using the Adddays method on the Get-Date . This gets us the value of 14 days ago

$now = Get-Date

$days = "14"

$TargetFolder = "y:\test"

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

Next step is to recursively query the Y:\test folder to get a list of files that are older than 14 days. In this sample code you can see I limited the $Files paramater to just *.bak, *.trn and *.txt , this is a safety mechanism to prevent mass deletions.

$Files = get-childitem $Targetfolder -include *.bak,*.trn,*.txt -Recurse | Where{$_.LastWriteTime -le "$Lastwrite"}

Then we do the removal using a Foreach loop to loop through the list of files and delete them.

if ($Files -ne $null)
{
	foreach ($file in $Files)
	{
		Remove-Item -path $File.Fullname -Verbose
	}
}

Adding in the Else to catch the error that would otherwise occur if there were no files to delete.

Else
{
Write-Host "Nothing to clean up"
}
#EndRegion

So there we have it, a simple script to move files to a folder and delete them when older than the required date. I’ve used this many times and it has always been quite fast and efficient. The full script can be downloaded from here