Created
November 13, 2017 11:20
-
-
Save Clijsters/ee681d0faa4a078244514f7dae92dda7 to your computer and use it in GitHub Desktop.
Create Backups using snapshots and symlinks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function snapshot() { | |
param( | |
[String]$Path, | |
[String]$Access, | |
[String]$BackupName | |
) | |
Write-Debug "Backing up $Path to $BackupName..." | |
#Create VSS Snapshot | |
$shadowCopy = (Get-WmiObject -List Win32_ShadowCopy).Create([System.IO.Directory]::GetDirectoryRoot($Path).ToString(), $Access) | |
Write-Verbose "Querying Win32_ShadowCopy for element with ID $($shadowCopy.ShadowID)" | |
$shadowCopyWmi = Get-WmiObject Win32_ShadowCopy | ? { $_.ID -eq $shadowCopy.ShadowID } | |
#Build valid path for link creation | |
$snapshotPath = $shadowCopyWmi.DeviceObject + "\" + $Path.Replace([System.IO.Directory]::GetDirectoryRoot($Path).ToString(), "") | |
#Build vallid target path | |
$targetPath = ("D:\BACKUP\") + $BackupName | |
Write-Verbose "Symlink target: $targetPath" | |
Write-Verbose "Snapshot location: $snapshotPath" | |
#Create Link | |
cmd /c mklink /d $targetPath "$snapshotPath" | |
} | |
Function New-Backup { | |
<# | |
.DESCRIPTION | |
Creates a VSS-based backup of a given folder. | |
The backup will be symlinked to D:\BACKUP\%DateTime_FolderName% | |
.PARAMETER path | |
Specifies the path to backup. The snapshot will be created for it's root direcory. | |
The symlink will point to the given path. | |
.EXAMPLE | |
Create-Backup -Path D:\myFiles\databases | |
#> | |
param( | |
[Parameter(Mandatory = $false)] | |
[string] $Path = (Get-Item -Path ".\").FullName | |
) | |
if (Test-Path $Path) { | |
Write-Verbose "Creating Snapshot for given path..." | |
[String]$target = [datetime]::Now.ToString("dd.MM.yy_HH-mm") + "_" + [System.IO.Path]::GetFileNameWithoutExtension($Path) | |
Write-Debug "Target: $target" | |
snapshot -Path $Path -Access "ClientAccessible" -BackupName $target | |
} | |
else { | |
[System.Management.Automation.ItemNotFoundException]::new("The Path specified for backup couldn't be found.") | |
} | |
} | |
New-Alias -Name Create-Backup -Verbose New-Backup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I am newbie on powershell, how do I feed parameters into this powershell script ?
I have tried .\script.ps1 from a powershell command line but it only replies with:
VERBOSE: Performing the operation "New Alias" on target "Name: Create-Backup Value: New-Backup".
I would like to modify it so that I am able to run this in task scheduler with a target path and a destination path.
thanks
Gavin