0

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"
Ocaso Protal
  • 19,362
  • 8
  • 76
  • 83
Darryl Wilson
  • 1,679
  • 2
  • 11
  • 7
  • `Where-Object { $_.LastWriteTime -lt (get-date).AddDays(-14) -and $_.LastWriteTime -gt (Get-Date).AddMonths(-13) } ` – Olaf May 03 '19 at 12:23
  • `-and` your conditions. 2weeks => `(Get-Date).AddDays(-14)`, 13 Month `(Get-Date).AddMonths(-13)` In a move you change the location not the filename/extension, see `Get-Help Move-Item` –  May 03 '19 at 12:25

1 Answers1

2

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

Theo
  • 57,719
  • 8
  • 24
  • 41