How to remove files by last write time with PowerShell

I am a developer from Nebraska in the US.
Search for a command to run...

I am a developer from Nebraska in the US.
No comments yet. Be the first to comment.
When you are in a flow, nothing is worse than having to stop to deal with a console error message. It would be great if the errors could be handled by the script and packaged into helpful messages. Happily, PowerShell offers this capability to catch,...

If you have ever forked a repository on github, you have likely encountered the terms merge and rebase when researching how to interact with the original repository. Merging and rebasing are two different methods to solve the same problem, namely, ho...

If you use a personal access token to authenticate to github, and you should be using one, you may have encountered the below error when trying to push updates to a remote repository. (refusing to allow a Personal Access Token to create or update wor...

This short guide is intended to flatten the git learning curve for a beginner. The guide will cover the basics of getting started with git on the command line. Cloning a Repository Cloning a repository is the git term for downloading a remote project...

If you have ever installed a new library or language on your mac, you have probably experienced the frustration of receiving “Command Not Found” when trying to use it in the terminal. This is especially challenging for beginners who may wonder what h...

Drive space is a finite resource, ask any server administrator. No one wants to see the message, “No space on disk”, when you are trying to save that last document. How can you clean up files that you don’t need? As always, PowerShell makes it simple.
This script will remove files by last write time, which is the last date and time the file was modified.
$Now=Get-Date
Get-Childitem C:\FilePath\*.* | Where-Object { $_.LastWriteTime -lt $Now.AddDays(-30) } | Remove-Item -Verbose
The first step is to get the time you want to use as the baseline for the delete, this is what you will compare against when telling the script what files to remove. In the example, this date and time is stored in the variable $Now. The Get-Date command will retrieve the date and time when the script is run.
The next step is to get a list of files that are candidates for removal. This is done with the Get-ChildItem command and the file path. This information is sent to the Where-Object command which determines which files meet the criteria. In the example, last write time is used along with $Now.AddDays(-30) which subtracts 30 days from the current date. Any files where the last write time is more than 30 days old are then sent to the Remove-Item command and deleted.