Skip to content

Instantly share code, notes, and snippets.

@Clijsters
Created November 13, 2017 11:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Clijsters/ee681d0faa4a078244514f7dae92dda7 to your computer and use it in GitHub Desktop.
Save Clijsters/ee681d0faa4a078244514f7dae92dda7 to your computer and use it in GitHub Desktop.
Create Backups using snapshots and symlinks
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
@pintail120
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment