PowerShell has tons of tricks of its sleeve. Here's how to use it to copy a folder and its contents, but omitting some of its folders, to a target folder.
PowerShell's syntax odd syntax is well in play here with what appear to be misplaced semicolons and extra dollar signs--but everything is necessary and correct. (To be fair, Bash's syntax is equally as odd).
This script shows how to:
- Declare a counter digit to ensure target folder uniqueness.
- Increment the target folder name with that counter to ensure folder uniqueness
- Check in a loop if the target exists
- Write messages to the console.
Microsoft's robocopy file utility and its mir
option is the primary enable for this script. robocopy mirrors the source directory tree and deletes destination files and directories that no longer exist in the source. The xd
option excludes a directory and can be used as many times as necessary. (xf
is also available to exclude files).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<# Copy a folder to another folder without overwriting previous backups. #> $number = 1 for (;$number -le 200;) { $target_folder = "d:\django-web-backup-$($number)" if (-not (Test-Path $target_folder)) { $target_folder = $target_folder + "\root" robocopy root $($target_folder) /mir /xd node_modules /xd .git write-host "Backup written to $($target_folder)" exit } write-host "$($target_folder) already exists." $number+=1 } |
Change the folder names as needed and save the code above to a file named backup.ps1
. To run this script, use
1 |
/.backup |