Powershell script for moving files
I needed to move a large number of files from one directory into an archive every month and only files over one 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.
Let me take through the steps I took to build the final 1 line script.
Lets get started
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 use a variable $(Get-Date) to get today’s date and the add -1 month (subtract a month) to get the date one month ago.
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\"
So, to review the command, we have 3 steps.
Step 1: We get a list of all files in the folder, and using the pipe we pass these results onto the next step.
Step 2: We then filter these to files older than a month and pass the results onto the move command.
Step 3: We take the output of the filter and use this list to move the files.
To Automate the process
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,
Thanks
Ian