【问题标题】:Powershell: Copying files from multiple folders created x days while maintaining folder structurePowershell:从创建 x 天的多个文件夹中复制文件,同时保持文件夹结构
【发布时间】:2018-12-11 20:20:56
【问题描述】:

我在使用 FOREACH 循环的 Powershell 复制期间维护文件夹结构时遇到问题,因为父文件夹下的某些文件夹需要 90 天前创建的数据,而其他文件夹需要 180 天。

$Folders_90Days = "C:\Admin\Ripley","C:\Admin\Android","C:\Admin\Bishop"
$Folders_180Days = "C:\Admin\Archer","C:\Admin\Figgis","C:\Admin\Pam"
$Dest = 'D:\Archive_Target'

FOREACH($path in $Folders_90Days){
$files = (Get-ChildItem $path | Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-90)})

ForEACH($file in $Files){
Copy-Item $file.FullName -destination $Dest -Recurse
}
#End ForEach Folders_90Days loop
}

复制运行时,将从源文件夹复制的数据直接复制到目标。
所以本质上Ripley中的数据直接复制到Archive_Target

如何让它在源文件夹成为目标文件夹的情况下复制?
示例:
D:\Archive_Target\Ripley
- 一直保持Source Ripley的文件夹结构?

【问题讨论】:

  • 我建议使用 Robocopy 而不是重新发明轮子。
  • 您将如何在 Powershell 中使用 Robocopy 来实现这一目标?稍后当所有内容都复制到目的地时,我将使用 PS 将其全部压缩到存档中。
  • 首先在 powershell 提示符下输入:robocopy /?

标签: powershell


【解决方案1】:

我创建了一个无需 xcopy 即可完成此任务的函数。

我把它放在允许并行处理的工作流中。

使用正则表达式,我得到了作为源代码基础的文件夹。如果路径不存在,则创建它,否则真正的肉在管道中。 获取源中的所有项目,如果比 AgeInDays 更旧,则通过管道将其复制到允许文件结构保持不变的容器中。

workflow Copy-ItemBasedOnCreation{
    Param(
        [string[]]$Sources,
        [string]$Desination,
        [int]$AgeInDays
    )

    foreach –parallel ($Source in $Sources){
        $FixedDesination = "$($Desination)$($Source -replace '.*\\')"
        if(!(Test-Path -Path $FixedDesination)){
            md $FixedDesination
        }
        Get-ChildItem  $Source -Recurse | ?{(($_.CreationTime).Day -gt $AgeInDays)} | Copy-Item -Destination $FixedDesination -Recurse -Container
    }
}

Copy-ItemBasedOnCreation -Sources @("C:\Users\Default\Desktop\Source\TEST1","C:\Users\Default\Desktop\Source\TEST2") -Desination "C:\Users\Default\Desktop\Destination\" -AgeInDays 90
Copy-ItemBasedOnCreation -Sources @("C:\Users\Default\Desktop\Source\TEST4","C:\Users\Default\Desktop\Source\TEST5") -Desination "C:\Users\Default\Desktop\Destination\" -AgeInDays 180

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2018-11-01
    • 1970-01-01
    相关资源
    最近更新 更多