Reputation: 799
I want to copy files that are over 30 minutes old from a live folder to an archive folder and retain the folder structure using powershell. I have this command so far but although it moves the files and folders it puts all the files in to the top level of the destination.
get-childitem -Recurse -Path "c:\input folder" | where-object {$_.CreationTime -lt (get-date).AddMinutes(-90)} | copy-item -destination "E:\output archive"
so if my source looks like this -
c:\input folder\sub1\filea.txt
c:\input folder\sub2\fileb.txt
c:\input folder\sub3\filec.txt
It currently looks like this with my command in the destination this is wrong as I want it to retain the folder structure -
e:\output archive\sub1\
e:\output archive\sub2\
e:\output archive\sub3\
e:\output archive\filea.txt
e:\output archive\fileb.txt
e:\output archive\filec.txt
It should look like this -
c:\output archive\sub1\filea.txt
c:\output archive\sub2\fileb.txt
c:\output archive\sub3\filec.txt
what is missing from my command?
Upvotes: 0
Views: 3148
Reputation: 200283
You need to preserve the partial path relative to the source folder when copying the files. Normally copy statements don't do that but copy the file from whatever (source) subfolder to the destination folder.
Replace the source folder part in the full name of each copied item with the destination folder:
$src = 'C:\input folder'
$dst = 'E:\output archive'
$pattern = [regex]::Escape($src)
$refdate = (Get-Date).AddMinutes(-90)
Get-ChildItem -Recurse -Path $src |
Where-Object { $_.CreationTime -lt $refdate } |
Copy-Item -Destination { $_.FullName -replace "^$pattern", $dst }
Upvotes: 1