copy files if modified

MarSim 21 Reputation points
2022-06-03T13:35:24.763+00:00

hi,

I'm scripting newbie I would need, for a project, to be able to have "online" the last 4 versions of some files ..

given the "parent" folder that contains them, I would like to copy the modified files, in sequence, to the Ver1, Ver2, Ver3, Ver4 folders

how can I proceed?

Windows for business Windows Server User experience PowerShell
Windows for business Windows Client for IT Pros User experience Other
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2022-06-03T17:49:44.867+00:00

    See if this works for you.

    $SourceFolder = 'C:\Temp\test'
    $BackupFolder = 'C:\Temp\test\Bkup'
    $versions = 3
    cls
    # insure that all of our version folders exist 
    for ($i = 1; $i -le $versions; $i++) {
        $vf = $BackupFolder + "\Ver" + $i
        if ((Test-Path $vf) -eq $false) {
            "Creating $vf" 
            $z = New-Item -Path $vf -ItemType Directory 
        }  
    }
    # Analyze files in source folder 
    $files = Get-ChildItem $SourceFolder -Filter '*.txt' -File      # this sample code looks at txt files 
    foreach ($f in $files) {
        "Processing {0}" -f $f.name
        # Let's see if we have a backup of this version 
        $v1 =  $BackupFolder + "\Ver1\" + $f.Name 
        $v1f = Get-Item $v1 -ErrorAction SilentlyContinue
        if ($v1f.LastWriteTime -ne $f.LastWriteTime) {     # is the ver1 file the same timestamp as the source file? 
            " Need to backup this file."
            for ($i = $versions -1; $i -gt 0; $i--)  {      # move ver3 to ver4, then ver2 to ver3, etc. 
                $src = $BackupFolder + "\Ver" + $i + "\" + $f.name 
                $dst =  $BackupFolder + "\Ver" + ($i + 1) + "\"
                try {
                    " Move $src to $dst" 
                    move-item  $src -Destination  $dst -Force -ErrorAction Stop
                    " Success."
                } catch {
                    " No backup version in $src" 
                }
            } 
            Copy-Item $f.FullName -Destination $v1           # finally backup the modified file to ver1 folder.     
            " Copied to $v1"
        }  
    }
    
        
    

1 additional answer

Sort by: Most helpful
  1. MarSim 21 Reputation points
    2022-06-07T07:56:17.06+00:00

    Thank you!

    it's what I needed, and from what I could try it works :-)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.