【问题标题】:use powershell to copy files and folders to archive folder older 30 minutes使用 powershell 将文件和文件夹复制到 30 分钟前的存档文件夹
【发布时间】:2015-05-11 11:20:12
【问题描述】:

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

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

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

c:\输入文件夹\sub1\filea.txt

c:\输入文件夹\sub2\fileb.txt

c:\输入文件夹\sub3\filec.txt

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

e:\输出存档\sub1\

e:\输出存档\sub2\

e:\输出存档\sub3\

e:\输出存档\filea.txt

e:\输出存档\fileb.txt

e:\输出存档\filec.txt

应该是这样的 -

c:\输出存档\sub1\filea.txt

c:\输出存档\sub2\fileb.txt

c:\输出存档\sub3\filec.txt

我的命令缺少什么?

【问题讨论】:

    标签: powershell get-childitem copy-item


    【解决方案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 }
    

    【讨论】:

    • 这行得通,但我只注意到一个问题。如果有打开的文件,脚本将停止。可以跳过打开的文件还是忽略错误?
    • @user2369812 “停止”是“挂起”还是“因错误而终止”?如果是后者,请尝试将-ErrorAction SilentlyContinue 添加到Copy-Item
    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多