In the following example I will demonstrate how to use Windows PowerShell to delete files based on days. Windows PowerShell is a new Windows command-line shell designed for a scripting environment. With Windows 7 and Windows Server 2008 R2, PowerShell is installed out off the box now.
Windows PowerShell has an interactive prompt and can be used in combination with scripts. I use “Windows PowerShell ISE” application to generate the script (PS1 extension). Notepad or any other text editor can be used as long the PS1 extension is used.
The following procedure requires that Executions Policy for the interactive PowerShell console is set to RemoteSigned. Please check the policy before starting with script.
Step 1 – Check the ExecutionPolicy for PowerShell
Get-ExecutionPolicy
If the output results in “Restricted” make sure the execute the following step.
Step 2 – Set ExecutionPolicy to RemoteSigned
Set-ExecutionPolicy RemoteSigned
Check again the the ExecutionPolicy and please make sure it stated “RemoteSigned”.
How to delete files older than X days?
Windows PowerShell is built on top of the .NET Framework common language runtime (CLR) and the .NET Framework. By combining different cmdlets, PowerShell can help with executing complex tasks.
In the following example I will use couple of built-in commands to search for files older than defined days and delete the files. This script can be useful for cleaning up some log files on a web server or deleting obsolete files.
Script logic
Define the parameters. For my example I am using C:\Applications\Logs folder where I want to delete files which are older than 7 days. I am also defining the LOG extension filter.
#----- define parameters -----# #----- get current date ----# $Now = Get-Date #----- define amount of days ----# $Days = "7" #----- define folder where files are located ----# $TargetFolder = "C:\Applications\Logs" #----- define extension ----# $Extension = "*.log" #----- define LastWriteTime parameter based on $Days ---# $LastWrite = $Now.AddDays(-$Days)
Get all files from the $TargetFolder and apply the $LastWrite filter
#----- get files based on lastwrite filter and specified folder ---#
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
For each file in $TargetFolder folder, run a foreach loop and delete the file.
foreach ($File in $Files)
{
if ($File -ne $NULL)
{
write-host "Deleting File $File" -ForegroundColor "DarkRed"
Remove-Item $File.FullName | out-null
}
else
{
Write-Host "No more files to delete!" -foregroundcolor "Green"
}
}
Create new file and name it Delete_Files_Older_Than_X_Days.PS1
I used Windows PowerShell ISE to create and test the new file. Make sure to define your parameter like days, folder and extension. For extension use * to include all files. Before assigning the script to a group policy, logon script or other distribution methods please make sure it works for you!
#----- define parameters -----#
#----- get current date ----#
$Now = Get-Date
#----- define amount of days ----#
$Days = "7"
#----- define folder where files are located ----#
$TargetFolder = "C:\Applications\Logs"
#----- define extension ----#
$Extension = "*.log"
#----- define LastWriteTime parameter based on $Days ---#
$LastWrite = $Now.AddDays(-$Days)
#----- get files based on lastwrite filter and specified folder ---#
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files)
{
if ($File -ne $NULL)
{
write-host "Deleting File $File" -ForegroundColor "DarkRed"
Remove-Item $File.FullName | out-null
}
else
{
Write-Host "No more files to delete!" -foregroundcolor "Green"
}
}
How to run the new script from Command Prompt or PowerShell console?
From Command Prompt run the powershell command with with path and file name of the script.
powershell -command "& 'C:/Applications/Delete_Files_Older_Than_X_Days.PS1'"
From PowerShell console go to the folder and run the script. For example:
PS C:\Applications> .\Delete_Files_Older_Than_X_Days.PS1
Make sure to test your modified version of this script. This PowerShell script works fine with my Windows environment based on Windows Server 2003 and Windows 7. I hope this post will help you finding your solution on the problem you want to solve. PowerShell options are endless.
References

Tim
This didn’t really work too well for me unless I used the FullName property of the $File object, and used a -recurse option on the Remove-Item cmdlet, like so:
foreach ($File in $Files) {
Remove-Item $File.FullName -recurse
}
These were problems for me because:
a) the working directory for my script was c:\bin, but my target directory was c:\tmp. So what was happening was I’d get an error on each call to Remove-Item, saying that c:\bin\ did not exist. The $File.FullName fixed that problem, FullName contains the full path to the file to be deleted.
b) Without the -recurse option on Remove-Item, you get a prompt asking you if you’re sure you want to remove the directory (if the target is a directory). This is a larger problem in that the parent folder may have an older modify date than it’s children folder, and unfortunately this script will simply delete the parent and all sub-children blindly, even if a new file is located in a sub-child directory. Not good in general cases but for my c:\tmp dir I can live with it.
Mike
Worked great! Thanks!
Chris
Worked perfectly as described, thanks very much!
Chris King
Typical, ‘here is an untested script that I cooked up without seeing it if worked’ post.
Thanks Tim. You understand that testing/debug is 90% of scripting.
Thomas G Mayfield
get-childitem | where -FilterScript {$_.LastWriteTime -le [System.DateTime]::Now.AddDays(-7)} | remove-item
Weaselspleen
@Chris King:
Typical, “here is a post where I criticize the article without having actually read it.”
Had you bothered to read it, you’d have noticed that this script is intended to do exactly one thing, and that is remove old Symantec antivirus definitions.
Here are the subtle clues which allowed me to figure this out:
1. The file mask specifies .zip and .def files
2. The target folder includes a Symantec path
3. The fact that he titles the script “RemoveScriptSymantec.ps1″
4. The fact that he SPECIFICALLY DESCRIBED EXACTLY WHAT IT IS FOR IN THE VERY FIRST PARAGRAPH.
Esteban!
Thank you.
I just added a condition to check that the file is not null.
foreach ($File in $Files) {
#Check for null
if ($file -ne $NULL){
#write-host “Deleting Transaction LOG: $File” -foregroundcolor “Red”;
Remove-Item $File | out-null
}
}
Ge-dadang
$Now = Get-Date
$Days = “9”
$TargetFolder = “\\svrmdectx12\USERS”
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder | Where {$_.LastWriteTime -le
“$LastWrite”} | sort-object LastWriteTime
$Files
“”
$Files.count
“”
foreach ($File in $Files)
{
$file12 = $file.name
If ($file12 -ne $null)
{
write-host “Deleting File $file12” -foregroundcolor “Red”;
#Remove-Item $TargetFolder\$File -recurse -force | out-
null
}
Else
{
“”
Write-host ” No more file to delete ”
“”
}
}
Larry Nicholson
Great stuff! Thank you
Chris King
@weaselspleen
Your right, I must have been is some mood that day. My only excuse is that there IS a lot of untested scripts floating around in posts.
This is obviously not one of them.
Sorry, Ivan.
Ivan Versluis
Dear all,
Thanks for your replies and comments. Information posted on my blog is provided AS IS. The script worked fine within my environment. I have modified this post which was almost three years old and made it more general then before. The initial script is still running on my Windows 2003 VM and deleting the files.
So thanks for the feedback. Maintaining such kind of blogs requires energy and time but seeing all of you here I am happy to do that.
With kind regards,
Ivan
Paul Wiegmans
Why do you test if a file is $Null? Why would Get-Childitem return a $null file? This makes no sense to me.