简体   繁体   中英

Copy Recently Modified Files with Folder Structure Using PowerShell

I'm new to PowerShell. Can someone please help me with my requirement as below. I have Folder, subFolders, and sub-subfolders,... and files inside each level of folders. If any file gets modified/created, I need to copy that modified/created file with the respective folder structure.

Eg, I have a folder structure like below.

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

Now if ComponentFile1 gets changed, then I need to copy folder structure only related to that file to my target folder. Like src/aura/Component/ComponentFile1.

I have tried something like this which is not working.

$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

Any Help on this appreciated.

Please try the code below.

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

What you want is easy achievable with robocopy instead of copy-item . It has the options for sysncing folders, purging deleted folders, and many others. Usage is something like this:

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

Some useful options:

/s - include non-empty subdirectories /e to include the all the subdirs (sometimes needed as content will be put there at build or test time) /b - backup mode - copy newr files only /purge - delete what was deleted in source folder

For all the parameters see robocopy docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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