Always step into a script development, validating along the way to a final result.
ls D:\temp2 -file
will return this…
Directory: D:\Temp
Mode LastWriteTime Length Name
-a---- Wed 07 Jun 02017 512 CombinedSources07Jun2017.txt
…
PS D:> ls D:\temp2 -file | where LastWriteTime -gt (get-date).AddDays(-60)
Now filtering based on date, give you the same results, just only the files in the date range
ls D:\temp -file | where LastWriteTime -gt (get-date).AddDays(-60) | Move-Item D:\temp1
Now let’s move those file, wait, cannot do this because we have not yet told the Move-Item cmdlet specifically what file to move, because we are not passing a filename. We are pass everything at once. That is not a thing.
As per the examples in the PowerShell help files…
Examples
Example 1: Move a file to another directory and rename it
PS C:>Move-Item -Path C:\test.txt -Destination E:\Temp\tst.txt
This command moves the Test.txt file from the C: drive to the E:\Temp directory and renames it from test.txt to tst.txt.
Example 2: Move a directory and its contents to another directory
PS C:\>Move-Item -Path C:\Temp -Destination C:\Logs
This command moves the C:\Temp directory and its contents to the C:\Logs directory. The Temp directory, and all of its subdirectories and files, then appear in the Logs directory.
Example 3: Move all files of a specified extension from the current directory to another directory
PS C:\>Move-Item -Path .\*.txt -Destination C:\Logs
This command moves all of the text files (*.txt) in the current directory (represented by a dot (.)) to the C:\Logs directory.
Example 4: Recursively move all files of a specified extension from the current directory to another directory
PS C:\>Get-ChildItem -Path ".\*.txt" -Recurse | Move-Item -Destination "C:\TextFiles"
So, that where clause is the problem child and we need to change it to pass the filenames, not a directory list.
Get the filtered names
(ls D:\temp -file | where LastWriteTime -gt (get-date).AddDays(-60)).FullName
returns
D:\temp\fsoVolume.docx
…
OK, now only getting files, let’s move them
(ls D:\temp -file | where LastWriteTime -gt (get-date).AddDays(-60)).FUllName | Move-Item D:\temp1
Dang error again, because we are trying to pass all at once, when we need to do this per filename.
(ls D:\temp -file | where LastWriteTime -gt (get-date).AddDays(-60)).FUllName |
% {Move-Item $_ D:\temp1}
Ahhhh, via a ForLoop, we iterate through the list and Move-Item likes that, because no errors
Let’s check
ls D:\Temp1
Directory: D:\Temp1
Mode LastWriteTime Length Name
-a---- Sat 18 Nov 02017 11686 fsoVolume.docx
Cool, mission accomplished.