Extending Robocopy

by Dec 27, 2016

PowerShell can add value to existing commands such as robocopy. Take a look at the below function–it uses robocopy to copy files, and adds the ability to perform a „Flat Copy“ as well as the option to open the destination folder after the copy is done:

#requires -Version 3.0

function Copy-FileWithRobocopy
    [string]$Filter = '*',
    [int]$RetryCount = 0,
    [string]$ExcludeDirectory = '',
  $Recurse = '/S'
  if ($NoRecurse) { $Recurse = '' }
  robocopy.exe $Source $Destination $Filter /R:$RetryCount $Recurse /XD $ExcludeDirectory
  if ($FlatCopy)
    Get-ChildItem -Path $Destination -Recurse -Filter $Filter | 
      Move-Item -Destination $Destination -Force
    Get-ChildItem -Path $Destination -Directory | 
      Remove-Item -Recurse -Force
  if ($Open)
    explorer $Destination

This would copy all log files from any subfolder inside the Windows folder to a new folder named c:\logs, and performs a flat copy:

PS>  Copy-FileWithRobocopy -Source $env:windir -Destination c:\logs -Filter *.log -FlatCopy -Open

Before you use this on production systems, take a look at how –FlatCopy works: it simply looks for any files inside the destination folder that match the specified filter, and moves them to the root, then deletes all folders.

So duplicate files will be overwritten, and if the destination folder contained other data before in subfolders, these will be deleted. It’s a very simple approach that works for many use cases but leaves a lot of room for improvement.

Twitter This Tip! ReTweet this Tip!