Skip to content

Instantly share code, notes, and snippets.

@searope
Created April 21, 2016 18:47
Show Gist options
  • Save searope/24eb7113e31a3b5e500a9155e7b4d3be to your computer and use it in GitHub Desktop.
Save searope/24eb7113e31a3b5e500a9155e7b4d3be to your computer and use it in GitHub Desktop.
$TotalNumberVersionsToKeep=100
$BackupFolder = "\\osgdesign\Studio\Windows\Users\v-senefe\Backup" # make sure there is no ending \
$ProjectFolder = "C:\DesignDepot.Git" # make sure there is no ending \
$ProjectFolderName = [System.IO.Path]::GetFileName($ProjectFolder)
Push-Location -Path $ProjectFolder
$changes = CMD.EXE /C git ls-files --modified --others --exclude-standard | Out-String
if ($changes.Length -eq 0){
Exit
}
Pop-Location
Push-Location -Path $BackupFolder
$dirs = Get-ChildItem | Where-Object {$_.Name -match '^.*\.[0-9]{4}$'} | Sort-Object -Property Name -Descending
foreach($d in $dirs){
$ext = [int32]::Parse([System.IO.Path]::GetExtension($d.Name).Substring(1))
# Write-Host $ext
if ($ext -ge $TotalNumberVersionsToKeep){
Remove-Item -Recurse -Force $d
}
$newName = $d.Name.Substring(0, $d.Name.Length-4) + "{0:D4}" -f ($ext+1)
Rename-Item $d -NewName $newName
}
foreach($file in ($changes -split '[\r\n]') |? {$_} | ForEach {$($_ -replace "/", "\")}){
$from = $ProjectFolder + "\" + $file
$to = $BackupFolder + "\$ProjectFolderName.0000\" + $file
$toDir = [System.IO.Path]::GetDirectoryName($to)
# Write-Host $from, $to, $toDir
if (!(Test-Path -path $toDir)) { New-Item $toDir -Type Directory }
Copy-Item $from -Destination $to
}
Pop-Location
@searope
Copy link
Author

searope commented Apr 21, 2016

powershell script to backup all changed files in git (modified or added) to specified folder
i use it in Task Scheduler to run every hour to be able to roll back or recover from accidental deletions or undos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment