Move Files in Powershell

Asked by At

Using the code below as a base (from another question) how can I move files between 2 dates eg : >2wks AND < 13 Months to another location. Also is it possible to restrict the file extension to be moved?

get-childitem -Path "E:\source" |
    where-object {$_.LastWriteTime -lt (get-date).AddDays(-31)} | 
    move-item -destination "F:\target"

1 Answers

2
Theo On

Restricting the files to fetch with Get-ChildItem can be done in several ways. The first is to use the -Filter parameter:

# set up the start and end dates
$date1 = (Get-Date).AddDays(-14)
$date2 = (Get-Date).AddMonths(-13)

# using -Filter if you want to restrict to one particular extension.
Get-ChildItem -Path "E:\source" -Filter '*.ext' |
    Where-Object {$_.LastWriteTime -lt $date1 -and $_.LastWriteTime -gt $date2} | 
    Move-Item -Destination "F:\target"

If you need to restrict to more than one extensions, you cannot do that with the -Filter parameter. Instead, you need to use the -Include parameter that can take an array of wilcard patterns.
Note that in order for the -Include to work, you must either also use the -Recurse switch, or have the path for Get-ChildItem end in \* like this:

# using -Include if you want to restrict to more than one extensions.
Get-ChildItem -Path "E:\source\*" -Include '*.ext1', '*.ext2', '*.ext3' |
    Where-Object {$_.LastWriteTime -lt $date1 -and $_.LastWriteTime -gt $date2} | 
    Move-Item -Destination "F:\target"

Then there's the -Exclude parameter that like the -Include also accepts a string array of wildcard parameters that will filter out the extensions you do NOT want.

If you need to filter on file attributes, like ReadOnly, Hidden etc., you could use the -Attributes parameter.

For these, have a look at the docs