使用powershell将文件和文件夹复制到30分钟以前的归档文件夹

时间:2015-05-11 11:20:12

标签: powershell get-childitem copy-item

我想将超过30分钟的文件从实时文件夹复制到存档文件夹,并使用powershell保留文件夹结构。到目前为止我有这个命令,但是虽然它移动了文件和文件夹,但它将所有文件放入目标的顶层。

get-childitem -Recurse -Path "c:\input folder" | where-object {$_.CreationTime -lt (get-date).AddMinutes(-90)} | copy-item -destination "E:\output archive"

所以,如果我的来源看起来像这样 -

  

c:\ input folder \ sub1 \ filea.txt

     

c:\ input folder \ sub2 \ fileb.txt

     

c:\ input folder \ sub3 \ filec.txt

目前我的命令在目的地看起来是这样的,这是错误的,因为我希望它保留文件夹结构 -

  

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

看起来应该是这样的 -

  

c:\ output archive \ sub1 \ filea.txt

     

c:\ output archive \ sub2 \ fileb.txt

     

c:\ output archive \ sub3 \ filec.txt

我的命令缺少什么?

1 个答案:

答案 0 :(得分:1)

复制文件时,需要保留相对于源文件夹的部分路径。通常,复制语句不会这样做,但会将文件从任何(源)子文件夹复制到目标文件夹。

使用目标文件夹替换每个复制项目的全名中的源文件夹部分:

$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 }
相关问题