PowerShell: Delete files after a number of days

I used to do a lot of “batch commands” back in the good old MS-DOS days. As with everything, technology advances and PowerShell is nothing short of amazing. Support for PowerShell  commandlets seems to pop up all over the place and I use it more and more to complete tasks.

Let’s say that you want to delete files from a folder, recursively, that have a creation date before a specific number of days.  How would you do it?  That’s right – PowerShell.

$path = 'F:\Program Files\Microsoft SQL Server\MSSQL12.SQLSERVER\MSSQL\Backup\Log'
$cutoffdays = (Get-Date).AddDays(-2)

Get-ChildItem $path -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $cutoffdays
} | Remove-Item

You can even look for files that have a specific extension:

$path = 'F:\Program Files\Microsoft SQL Server\MSSQL12.SQLSERVER\MSSQL\Backup\Log'
$cutoffdays = (Get-Date).AddDays(-2)
$extension = '.trn'

Get-ChildItem $path -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $cutoffdays -and $_.Extension -ieq $extension
} | Remove-Item

There are a number of other parameters and options. Give it a shot.

How to determine the version of PowerShell that is installed?

You can see the version of the PowerShell Engine by using the $PSVersionTable.PSVersion table. If you run Get-Help about_Automatic_Variables and read the contents of the $PSVersionTable you will get the following information:

Contains a read-only hash table that displays details about the version of Windows PowerShell that is running in the current session. The table includes the following items:
CLRVersion: The version of the common language runtime (CLR)
BuildVersion: The build number of the current version
PSVersion: The Windows PowerShell version number
WSManStackVersion: The version number of the WS-Management stack
PSCompatibleVersions: Versions of Windows PowerShell that are compatible with the current version
SerializationVersion: The version of the serialization method
PSRemotingProtocolVersion: The version of the Windows PowerShell remote management protocol