简体   繁体   中英

use powershell to copy files and folders to archive folder older 30 minutes

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?

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM