PowerShell: Synchronizing a Folder (and Sub-Folders) Part 2

I wrote about a script to synchronise the contents of one folder to another here.  It worked as a quick and simple backup script and it would replicate files, deletions and sub-folders.  I’ve used it quite a bit since that post and I’ve made some special modifications myself.

Details after the break.

Update : I’ve revisited this script a few times with new additions and modifications.The latest full version of the script is here.  That post also includes links covering the other revisions to the script.

The main new addition is the use of an exceptions list so certain files, folders or wildcards aren’t synced.  This was due to a few large folders I didn’t want to backup (like the Iphone backups in AppData).

function Check-Exceptions
{
param
(
[parameter(Mandatory=$True)]
[string]$TestPath
)
Write-Verbose "Checking $TestPath"
$Result=($Exceptions | % {$TestPath -like $_}) -contains $True
If ($Result) {Write-Verbose "Listed in Exceptions List, skipping."}
$Result
}

This function checks a passed file path against an array of exceptions ($Exceptions).  If the current path matches an exception then the function returns $False.  Note I use -like so that wildcards can be used in the exception list.

Write-Verbose is in there so I can monitor what the script is doing with the -Verbose flag.

$Exceptions is defined as an array;

$Exceptions=@("*.jpg","*.txt")

Here I’ve defined it so that jpegs and txt files are skipped.

The last change is modifying the lists of source and target files/folders to backup:

    $SourceFiles+=$SourceList | ? {$_.PSIsContainer -eq $False -and (!(Check-Exceptions $_.FullName))}
    $TargetFiles+=$TargetList | ? {$_.PSIsContainer -eq $False -and (!(Check-Exceptions $_.FullName))}
    $SourceFolders+=$SourceList | ? {$_.PSIsContainer -eq $True -and (!(Check-Exceptions $_.FullName))}
    $TargetFolders+=$TargetList | ? {$_.PSIsContainer -eq $True -and (!(Check-Exceptions $_.FullName))}

Now it only adds them to the relevant list if they’re the right type (a container for folders or not a container for files) AND they’re not listed in $Exceptions (checked with the function above).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: