【问题标题】:Copy Recently Modified Files with Folder Structure Using PowerShell使用 PowerShell 复制具有文件夹结构的最近修改的文件
【发布时间】:2019-09-07 12:04:29
【问题描述】:

我是 PowerShell 新手。有人可以帮我解决我的要求,如下所示。 我在每个级别的文件夹中有文件夹、子文件夹和子子文件夹……和文件。 如果任何文件被修改/创建,我需要使用相应的文件夹结构复制该修改/创建的文件。

例如,我的文件夹结构如下所示。

src
├── classes
│   └── ClassFile1(file)
├── objects
│   └── ObjectFile1(file)
└── Aura
    └── Component
        ├── ComponentFile1(file)
        └── ComponentFile2(file)

现在,如果 ComponentFile1 发生更改,那么我需要将仅与该文件相关的文件夹结构复制到我的目标文件夹。比如 src/aura/Component/ComponentFile1。

我尝试过类似的方法,但不起作用。

$Targetfolder= "C:\Users\Vamsy\desktop\Continuous Integration\Target"

$Sourcefolder= "C:\Users\Vamsy\desktop\Continuous Integration\Source"

$files = get-childitem $Sourcefolder -file | 
          where-object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5) }|
          Copy-Item -Path $files -Destination $Targetfolder -recurse -Force

对此的任何帮助表示赞赏。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    使用 robocopy 而不是 copy-item 可以轻松实现您想要的。 它具有同步文件夹、清除已删除文件夹和许多其他选项。 用法是这样的:

    $source = 'C:\source-fld'
    $destination = 'C:\dest-fld'
    $robocopyOptions = @('/NJH', '/NJS') #just add the options you need
    $fileList = 'test.txt' #optional you can provide only some files or folders or exclude some folders (good for building a project when you want only the sourcecode updated)
    
    Start robocopy -args "$source $destination $fileList $robocopyOptions"
    

    一些有用的选项:

    /s - 包括非空子目录 /e 包含所有子目录(有时需要,因为内容将在构建或测试时放在那里) /b - 备份模式 - 仅复制较新的文件 /purge - 删除源文件夹中已删除的内容

    所有参数见robocopy docs

    【讨论】:

    • 感谢您的回复。我曾尝试使用 RoboCopy,但在我的场景中,我需要最新修改的文​​件或最近 5 分钟内修改的文件。使用 Robocopy,我们可以过滤到天数/日期,但不能过滤到我认为的分钟数。所以我被 RoboCopy/XCopy 卡住了。
    【解决方案2】:

    请尝试下面的代码。

    $srcDir = "C:\Users\Vamsy\desktop\Continuous Integration\Target"
    $destDir = "C:\Users\Vamsy\desktop\Continuous Integration\Source"
    
    Get-ChildItem $srcDir -File -Recurse |
    Where-Object LastWriteTime -gt (Get-Date).AddMinutes(-5) |
    ForEach-Object {
        $destFile = [IO.FileInfo]$_.FullName.Replace($srcDir, $destDir)
        if($_.LastWriteTime -eq $destFile.LastWriteTime) { return }
        $destFile.Directory.Create()
        Copy-Item -LiteralPath $_.FullName -Destination $destFile.FullName -PassThru
    }
    

    【讨论】:

    • 非常感谢@rokumaru 你让我过得愉快..!!
    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多