簡體   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