Skip to content

Instantly share code, notes, and snippets.

@pandieme
Created August 3, 2022 09:52
Show Gist options
  • Save pandieme/95808f056876e8b64b5e1e33444699af to your computer and use it in GitHub Desktop.
Save pandieme/95808f056876e8b64b5e1e33444699af to your computer and use it in GitHub Desktop.
function Backup-Path ([System.IO.FileInfo]$Path, [System.IO.FileInfo]$BackupDirectory) {
if (-not ($Directory = Get-Item -Path $Path -ErrorAction SilentlyContinue)) { return Write-Warning "Unable to find directory [$Path]" }
if (-not $BackupDirectory) { $BackupDirectory = $Directory.Parent.FullName }
if (-not (Test-Path -Path $BackupDirectory)) { New-Item -Path $BackupDirectory -ItemType Directory > $null }
$ExistingBackups = Resolve-Path -Path "$(Join-Path -Path $BackupDirectory -ChildPath $($Directory.Name))*" | Where-Object { $_ -notlike $Directory.FullName }
[int]$Count = 1
while ($ExistingBackups -like (Join-Path -Path $BackupDirectory -ChildPath "$($Directory.Name)$("$Count".PadLeft(2, '0'))")) { $Count++ }
$BackupPath = Join-Path -Path $BackupDirectory -ChildPath "$($Directory.Name)$("$Count".PadLeft(2, '0'))"
$Directory | Copy-Item -Destination $BackupPath -Recurse
Write-Host "BACKUP: [$($Directory.FullName)] copied to [$BackupPath]"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment