Copy a folder with PowerShell

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).

Change the folder names as needed and save the code above to a file named backup.ps1. To run this script, use

Leave a Comment

Your email address will not be published. Required fields are marked *