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