I needed to move a large number of files from one directory into an archive every month and only files over 1 month old.
Although this in itself is not a hard task I wanted to automate it in a script and thought it was time to learn a bit of Powershell.
The first part of the command is to get a list of files in the folder. I found the command I needed was Get-Childitem.
Get-Childitem -Path "C:\CurrentPath\" -Recurse
This scans the folder in C:\CurrentPath and gets a list of files.
I now need to check the date of these files and only scan for files older than 1 month. The query for this uses the lastwritetime:
Where lastwritetime -LT $(Get-Date).AddMonths(-1)
We put them together through a pipe (|) and get:
Get-Childitem -Path "C:\CurrentPath\" -Recurse | Where lastwritetime -LT $(Get-Date).AddMonths(-1)
I now need to move this list of files to another folder. For this we can use the Move-Item command:
Move-Item -Destination "C:\Moved\"
We put it all together, with another pipe, to get the full command:
Get-Childitem -Path "C:\CurrentPath\" -Recurse | Where lastwritetime -LT $(Get-Date).AddMonths(-1) | Move-Item -Destination "C:\Moved\"
I saved this file as movefiles.ps1 then created a scheduled task to run powershell.exe with the following arguments:
-ExecutionPolicy Bypass -File C:\Test\movefiles.ps1
Schedule this to run as frequently as you want and there you have it, a scheduled task to move old files to an archive on a regular basis.
Hope this help, and if it does please leave a comment below,