繁体   English   中英

使用 PowerShell 复制具有文件夹结构的最近修改的文件

[英]Copy Recently Modified Files with Folder Structure Using PowerShell

我是 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

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

请尝试下面的代码。

$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
}

使用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 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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