August 19, 2009

Backup files/folder structure with Powershell

I was asked to look at a network share and backup the share and folder structure exactly how it is laid out to another location. I am sure this probably could be written with less code, but here is what I did.
$sourceDir = '\\MySrcShare\d$\\MySrcFolder'
$backupDir = 'K:\DestShare\Bkp'

function NormalizePath($path)
{
if($null -eq $path)
{
return $path
}

[System.IO.Path]::GetDirectoryName($path + "\")
}

$sourceDir = NormalizePath($sourceDir)
$backupDir = NormalizePath($backupDir)

$backupDir = [System.IO.Path]::Combine($backupDir, [System.IO.Path]::GetFileName($sourceDir))


dir $sourceDir -Recurse | % {

$relativePath = $_.FullName.Substring($sourceDir.length + 1)
$dest = [System.IO.Path]::Combine($backupDir, $relativePath)

if(Test-Path $_.FullName -PathType container)
{
New-Item -Path $dest -ItemType Directory -ErrorAction SilentlyContinue
}
else
{
$ext = [System.IO.Path]::GetExtension($_);

if(($ext.ToLower() -eq '.xml') -or ($ext.ToLower() -eq '.config'))
{
Copy $_.FullName -Destination $dest
}
}
}
This will copy the folder structure of source (including all sub-directories) to the destination and it will also copy *.config and *.xml files to their respective folders on the destination drive.

Anyone know how to tweak this or make it smaller?

No comments:

Post a Comment