PowerShell: Create Daily VSS Snapshot of Volumes on Local Windows Machine

<# Daily-VSS-Snapshots.ps1

Functions:
1. Dynamically detect all volumes on local machine
2. Dynamically take snapshots of each volume and mount them onto C:\Snapshots\$hostname\$volumeLabel\$snapshotTimeStamp
3. Copy symlinks of those local VSS client access links to a network share in this format (\\Snapshots\FileServerClusters\$clusterName\$hostname\$volumeLabel\$timeStamp)
4. Remove all previous snapshots that are older than retention period

Limitations:
1. VSS must be available on the host Windows machine
2. PowerShell version 3.0 or higher is assumed

Technical considerations:
1. This program should not be used to replace an Enterprise Grade servers backup system (e.g. Veeam, Veritas, Rubik).
2. WARNING: locally mounted snapshots will NOT be recoverable when the server itself becomes inoperable.

Quick Notes:
# command to delete all VSS Snapshots on the local system
vssadmin delete shadows /all /Quiet
#>

# Init variable to store local volume labels: this returns all fixed local volumes, excluding CD Roms, USB drives, and C:\
#$cdRomDrives=Get-CimInstance Win32_LogicalDisk | ?{ $_.DriveType -eq 5} | select DeviceID
$driveLettersExclusion="[BC]\:"
#$localVolumes=(Get-CimInstance Win32_LogicalDisk | ?{ $_.DriveType -eq 3}).DeviceID|Where{$_ -notmatch $driveLettersExclusion} #requires PowerShell version 3.0+
$localVolumes=Get-WmiObject Win32_LogicalDisk | ?{ $_.DriveType -eq 3}|Where{$_.DeviceID -notmatch $driveLettersExclusion}|Select DeviceID|%{$_.DeviceID} #PowerShell 2.0 compatible

# Set snapshot root directory variable
$localSnapshotDirectory="C:\Snapshots"
$remoteSnapshotDirectory="\\Snapshots\FileServerClusters"

# Set Retention Period
$retentionPeriod=7;

# Set hostname
$hostname=$env:computername

################################## Excuting Program as an Administrator ####################################
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "Black"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator

# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";

# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;

# Indicate that the process should be elevated
$newProcess.Verb = "runas";

# Start the new process
[System.Diagnostics.Process]::Start($newProcess);

# Exit from the current, unelevated, process
exit
}

Write-Host -NoNewLine "Running as Administrator..."
################################## Excuting Program as an Administrator ####################################

# Adding Prerequisite Microsoft Cluster
Function installFailoverClustersModule{
if (!(get-module -Name "FailoverClusters") ){
Try{
Import-Module FailoverClusters | out-null;
}
catch{
# On error, install the missing module
Install-WindowsFeature RSAT-Clustering-MGMT | out-null;
Install-WindowsFeature RSAT-Clustering-PowerShell | out-null;
Import-Module FailoverClusters | out-null;
}
}

function enableR2RSymbolicLinks{
<# Preemptively resolve this error
\\FILESHERVER\SomeShare is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions.
The symbolic link cannot be followed because its type is disabled.
#>

# Enable Remote to remote symlink following if it's not already set
$r2rEnabled=fsutil behavior query SymlinkEvaluation | select-string -Pattern "Remote to remote symbolic links are enabled."
$r2lEnabled=fsutil behavior query SymlinkEvaluation | select-string -Pattern "Remote to local symbolic links are enabled."
if (!($r2rEnabled) -or !($r2lEnabled)){
write-host "`Symbolic links following is disabled.`nEnabling this feature..."
fsutil behavior set SymlinkEvaluation R2R:1;
fsutil behavior set SymlinkEvaluation R2L:1
write-host "`nThis is now the system's settings after the change:"
fsutil behavior query SymlinkEvaluation
}
}


function checkDiskFree{
[cmdletbinding()]
param(
[string]$volume="C:\",
[string]$targetNode="localhost"
)

<#
Excerpt from http://technet.microsoft.com/en-us/library/ee692290(WS.10).aspx:

"For volumes less than 500 megabytes, the minimum is 50 megabytes of free space.
For volumes more than 500 megabytes, the minimum is 320 megabytes of free space.
It is recommended that least 1 gigabyte of free disk space on each volume if the volume size is more than 1 gigabyte."

#>

# Import variables
$thisNode=$targetNode

# Fix targetVolume input if it's missing the suffix
if ($volume -like "*\"){$thisVolume=$volume.Substring(0,$volume.Length-1)}else{$thisVolume=$volume}

# Obtain disk information
$diskObject = Get-WmiObject Win32_LogicalDisk -ComputerName $thisNode -Filter "DeviceID='$thisVolume'"
$diskFree=[Math]::Round($diskObject.FreeSpace / 1MB)
$diskSize=[Math]::Round($diskObject.Size / 1MB)

switch ($diskSize){
{$diskSize -ge 1024} {if ($diskFree -gt 1024){$feasible=$True;}else{$feasible=$False;};;break;}
{$diskSize -ge 500} {if ($diskFree -gt 320){$feasible=$True;}else{$feasible=$False;};;break;}
{$diskSize -lt 500} {if ($diskFree -gt 50){$feasible=$True;}else{$feasible=$False;};break;}
}

return $feasible
}

function removeSnapshots{
[cmdletbinding()]
param(
[int]$daysOlderThan=365
)

# Remove links older than X days
function removeLinks{
[cmdletbinding()]
param(
[string]$snapshotRootDirectory="C:\Snapshots",
[int]$olderThanXDays=365
)
$allSymlinks=Get-ChildItem $snapshotRootDirectory -Recurse -Depth 3 -ErrorAction SilentlyContinue|Where-Object {($_.Attributes -match "ReparsePoint")}

foreach ($link in $allSymLinks){
$creationTime=$link.CreationTime
$thisSymlink=$link.FullName
$removeSymlink=$creationTime -lt (Get-Date).AddDays(-$olderThanXDays)

# Remove symlink if condition is true
if ($removeSymlink){
(Get-Item $thisSymlink).Delete()
"Shadow link $thisSymlink with creation time of $creationTime has been removed."
}else{
"Shadow link $thisSymlink with creation time of $creationTime has NOT been removed."
}
}
}

# Remove old snapshots
function deleteOldSnapshots{
[cmdletbinding()]
param(
[int]$olderThanXDays=365
)
$allSnapshots=Get-WmiObject Win32_Shadowcopy

$allSnapshots | ForEach-Object {
$snapshotDate = $_.InstallDate
$snapshotID = $_.ID
$snapshotDateTimeValue = [management.managementDateTimeConverter]::ToDateTime($snapshotDate)
$thisClientAccessibleValue = $_.ClientAccessible
$currentDate = Get-Date
$timeSpan = New-TimeSpan $snapshotDateTimeValue $currentDate
$days = $timeSpan.Days

If ($days -ge $olderThanXDays -and $thisClientAccessibleValue -eq "True") {
$_.Delete()
"$snapshotID with date stamp of $snapshotDate has been deleted."
} else{
"$snapshotID with date stamp of $snapshotDate has NOT been deleted."
}
}
}

removeLinks -snapshotRootDirectory $remoteSnapshotPath -olderThanXDays $daysOlderThan
removeLinks -snapshotRootDirectory $localSnapshotPath -olderThanXDays $daysOlderThan
deleteOldSnapshots -olderThanXDays $daysOlderThan
}

function createNewSnapshot{
[cmdletbinding()]
param(
[string]$targetVolume="C:\",
[string]$label=$volumeLabel,
[string]$localShapshot="$localSnapshotPath\$hostname\$volumeLabel\$(Get-Date -Format 'yyyy-MM-dd_hh.mm.ss')",
[string]$remoteSnapshot="$remoteSnapshotPath\$hostname\$volumeLabel\$(Get-Date -Format 'yyyy-MM-dd_hh.mm.ss')"
)

# Create snapshot directory
New-Item -ItemType Directory -Force -Path "$localSnapshotPath\$hostname\$volumeLabel\" | Out-Null;
New-Item -ItemType Directory -Force -Path "$remoteSnapshotPath\$hostname\$volumeLabel\" | Out-Null;

# Fix targetVolume input if it's missing the suffix
if (!($targetVolume -like "*\")){$targetVolume+="\"}

# Create the VSS snapshot
$shadowCopyClass=[WMICLASS]"root\cimv2:win32_shadowcopy";
$thisSnapshot = $shadowCopyClass.Create($targetVolume, "ClientAccessible");
$thisShadow = Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $thisSnapshot.ShadowID };
$thisShadowPath = $thisShadow.DeviceObject + "\";

# Make links to this snapshot
#cd $snapshotPath | out-null
cmd /c mklink /d $localShapshot $thisShadowPath;
cmd /c mklink /d $remoteSnapshot $localShapshot;
#cmd /c mklink /d $snapshotPath $thisShadowPath;
<# PowerShell version 5.0 required
+-----------------------+-----------------------------------------------------------+
| mklink syntax | Powershell equivalent |
+-----------------------+-----------------------------------------------------------+
| mklink Link Target | New-Item -ItemType SymbolicLink -Name Link -Target Target |
| mklink /D Link Target | New-Item -ItemType SymbolicLink -Name Link -Target Target |
| mklink /H Link Target | New-Item -ItemType HardLink -Name Link -Target Target |
| mklink /J Link Target | New-Item -ItemType Junction -Name Link -Target Target |
+-----------------------+-----------------------------------------------------------+

SymbolicLink (modern) supports UNC paths, while Junction (older) does not.
#>
"Snapshot of $targetVolume has been made and it's accessible at this path: $remoteSnapshot"

# Export variables that this specific snapshot can be targeted and removed
#$GLOBAL:shadow=$thisShadow;
#$GLOBAL:snapshot=$thisSnapshot;
}

function proceed{
installFailoverClustersModule;
$clusterName=(get-cluster).name
$GLOBAL:localSnapshotPath="$localSnapshotDirectory\$clusterName"
$GLOBAL:remoteSnapshotPath="$remoteSnapshotDirectory\$clusterName"

New-Item -ItemType Directory -Force -Path $remoteSnapshotPath | Out-Null;
New-Item -ItemType Directory -Force -Path $localSnapshotPath | Out-Null;

enableR2RSymbolicLinks;
if ((get-item $localSnapshotPath) -and (get-item $remoteSnapshotPath) -and ($localVolumes)){
$localVolumes|%{
$GLOBAL:volumeLetter="$_"[0];
$GLOBAL:volumelabel="Volume_$volumeLetter`_$((get-volume -DriveLetter $volumeLetter).FileSystemLabel)";
if (!($volumeLabel)){$volumelabel="Volume_$volumeLetter"};
$snapshotLink="$localSnapshotPath\$hostname\$volumeLabel\$(Get-Date -Format 'yyyy-MM-dd_hh.mm.ss')";
$snapshotRemoteCopy="$remoteSnapshotPath\$hostname\$volumeLabel\$(Get-Date -Format 'yyyy-MM-dd_hh.mm.ss')"

if(checkDiskFree -volume $_){
createNewSnapShot -targetVolume $_ -label $volumeLabel -localShapshot $snapshotLink -remoteSnapshot $snapshotRemoteCopy;
}else{"Volume $_ does NOT have sufficient disk space available for taking snapshots."}
}
removeSnapshots -daysOlderThan $retentionPeriod
}else{"Program aborted due to missing items."}
}

proceed;

Leave a Reply

Your email address will not be published. Required fields are marked *