<# VSS-Snapshots-on-Microsoft-File-Server-Clusters_v0.0.1.ps1
# Author: KimConnect.com
Functions:
1. Create snapshots of all volumes on a file server - script is meant to be triggered via Windows Scheduled Tasks daily
2. Mount all snapshots onto a local folder as well as a network share
3. Automatic maintenance by removing snapshots that are exired
4. Since SMB client access points (virtual file server roles) can move dynamically, each instance of execution of this script will regenerate updated links
Limitations:
1. VSS must be available on the target 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. Locally mounted snapshots will NOT be recoverable when the storage array or iSCSI sources become inoperable or deleted.
Quick Notes:
# command to purge 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="[C]\:"
#$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 variables
$localSnapshotDirectory="C:\Snapshots";
$localSnapshotDirectoryTransformed="\\$env:computername\C$\Snapshots"
$remoteSnapshotDirectory="\\FILESERVER2020\FileServerClusters\Snapshots"
# Set Retention Period
$retentionPeriod=30;
# Set hostname
$hostname=$env:computername
# Other variables
$dateStamp=get-date -Format yyyy-MM-dd-HH.MM.ss;
$thisComputer=$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 importModuleFailoverClusters{
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 https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/ee692290(v=ws.10)?redirectedfrom=MSDN:
"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 cleanupSnapshots{
[cmdletbinding()]
param(
[int]$daysOlderThan=90
)
if(!($remoteSnapshotPath)){$remoteSnapshotPath="\\Snapshots\FileServerClusters\$((get-cluster).name)"}
if(!($localSnapshotPath)){$localSnapshotPath="C:\Snapshots\$((get-cluster).name)"}
# Remove links older than X days
function deleteExpiredLinks{
[cmdletbinding()]
param(
[string]$snapshotRootDirectory="C:\Snapshots\$((get-cluster).name)",
[int]$olderThanXDays=90
)
# Remove dead links
$deadLinkMessages="";
$allSymlinks=(Get-ChildItem $snapshotRootDirectory -Recurse -Depth 2 -ErrorAction SilentlyContinue|Where-Object {($_.Attributes -match "ReparsePoint")}).FullName
$deadLinkMessages=$allSymlinks|%{ if(!(test-path "$_\*")){
try{
[IO.Directory]::Delete($_); # This is the preferred method to remove reparse points
}catch{
$parentFolder=Split-Path $_ -Parent;
[IO.Directory]::Delete($parentFolder);
}
if(!(test-path $_)){
$deadLinkMessage="Removed dead link: $_`r`n";
$deadLinkMessage;
}else{
$deadLinkMessage="Unable to remove dead link: $_`r`n";
write-host $deadLinkMessage;
};
}
}
# Remove empty parent directories
$emptyDirectoryMessages="";
$parentDirectories=(Get-ChildItem $snapshotRootDirectory -Recurse -Depth 2 -ErrorAction SilentlyContinue|?{$_.PSisContainer -and $_.Attributes -notmatch "ReparsePoint"}).FullName
$emptyDirectoryMessages=$parentDirectories|%{ $directoryChildren = Get-ChildItem $_;
if ($directoryChildren.count -eq 0){
(Get-Item $_).Delete();
$emptyDirectoryMessage="Removed empty folder: $_`r`n";
$emptyDirectoryMessage;
}
}
<#
# Remove remaining expired links
$remainingSymlinks=Get-ChildItem $snapshotRootDirectory -Recurse -Depth 2 -ErrorAction SilentlyContinue|Where-Object {($_.Attributes -match "ReparsePoint")}
foreach ($link in $remainingSymlinks){
$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()
write-host "Shadow link $thisSymlink with creation time of $creationTime has been removed."
}else{
write-host "Shadow link $thisSymlink with creation time of $creationTime has NOT been removed."
}
}
#>
$deletedLinkMessages=$deadLinkMessages+$emptyDirectoryMessages;
return $deletedLinkMessages;
}
# Remove old snapshots
function deleteExpiredSnapshots{
[cmdletbinding()]
param(
[int]$olderThanXDays=90
)
$allSnapshots=Get-WmiObject -Class win32_shadowcopy|?{$_.ClientAccessible -eq $true}
#$driveLetterSnapshotsAssociation = Get-WmiObject Win32_Volume -Filter "DriveType=3" |?{$_.DriveLetter -ne $null}| select DriveLetter,Label, DeviceID | Sort DriveLetter;
$results=$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 -gt $olderThanXDays) {
#$_.Delete() # does nothing
#invoke-expression "vssadmin delete shadows /for=$volumePath /shadow=$snapshotID /quiet" # doesn't work, must invoke from cmd.exe
# Remove a single snapshot
write-host "Removing snapshot Id $snapshotID...";
# This is the workaround method to avoid the behavior of antivirus terminating sessions upon invoking the snapshot removal procedure
$newSession=New-PSSession
Invoke-Command -Session $newSession -ScriptBlock{param($snapshotID);vssadmin delete shadows /Shadow=$snapShotId /quiet} -args $snapshotID
$newSession|Remove-PSSession
# Validation
$currentSnapshotIds=(Get-WmiObject -Class win32_shadowcopy|?{$_.ClientAccessible -eq $true}).ID
if(!($snapshotID -in $currentSnapshotIds)){
$result="Snapshot Id $snapshotID with date stamp of $snapshotDateTimeValue has been removed as it's older than $olderThanXDays days.`r`n";
$result;
}else{
$result="There were errors while removing snapshot Id $snapshotID.";
write-host $result;
}
}else{
$result2="$snapshotID with date stamp of $snapshotDateTimeValue has NOT been deleted as it's newer than $olderThanXDays days.";
write-host $result2;
}
}
return $results;
}
$snapshotRemovalMessages=deleteExpiredSnapshots -olderThanXDays $daysOlderThan;
$deletedRemoteLinkMessages=deleteExpiredLinks -snapshotRootDirectory $remoteSnapshotPath -olderThanXDays $daysOlderThan;
$deletedLocalinkMessages=deleteExpiredLinks -snapshotRootDirectory $localSnapshotPath -olderThanXDays $daysOlderThan;
if(!($snapshotRemovalMessages)){$snapshotRemovalMessages="No snapshots removed."}
if(!($deletedRemoteLinkMessages)){$deletedRemoteLinkMessages="No remote links removed.`r`n"}
if(!($deletedLocalinkMessages)){$deletedLocalinkMessages="No local links removed.`r`n"}
$messages="Expired Link Maintenance Messages:`r`n---------`r`n"+$deletedRemoteLinkMessages+$deletedLocalinkMessages+$snapshotRemovalMessages
return $messages;
}
function createNewSnapshot{
[cmdletbinding()]
param(
[string]$targetVolume
#[string]$label=$volumeLabel,
#[string]$localLinkPrefix,
#[string]$transformedLocalLinkPrefix,
#[string]$remoteLinkPrefix
)
# Create directories if they don't already exist
#$remoteLinkParentDirectory=split-path $remoteLink -Parent
#$localSnapshotParentDirectory=split-path $localShapshot -Parent
#New-Item -ItemType Directory -Force -Path $localLinkPrefix | Out-Null;
#New-Item -ItemType Directory -Force -Path $remoteLinkPrefix | Out-Null;
# Fix targetVolume input if it's missing the suffix
if ($targetVolume[$targetVolume.length-1] -ne "\"){$targetVolume+="\"}
#write-host "please check these links:`nlocalSnapshotPath: $localSnapshotPath`ntransformedLocalPath: $transformedLocalPath`nremoteLink: $remoteLink"
write-host "Initiating 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 + "\";
<#
write-host "Creating links..."
$localShapshot="$localLinkPrefix\$shadowTimeStamp";
$remoteLink="$remoteLinkPrefix\$shadowTimeStamp";
$transformedLocal="$transformedLocalLinkPrefix\$shadowTimeStamp";
# Creating symlink
$voidOutput=cd C:
#$voidOutput=cmd /c mklink /d $shadowMount $thisShadowPath | Out-Null
$voidOutput=cmd /c mklink /J $localShapshot $thisShadowPath;
$voidOutput=cmd /c mklink /d $remoteLink $transformedLocal;
# Validate
$success=(gci $localSnapshot) -and (gci $remoteLink)
if ($success){
write-host "Shadow of $targetVolume has been made and it's accessible at this local file system (LFS): $shadowMount."
}else{
write-host "VSS Snapshot links have failed."
}
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.
Junction has one feature that symlinks do not have: functional Remote-to-Local Following!
This has made it possible to mount local snapshots as UNC paths. The trick is to combine
the features of both junctions and symlinks.
#>
# Export variables that this specific snapshot can be targeted and removed
if($thisShadow){
$GLOBAL:shadow=$thisShadow;
$GLOBAL:snapshot=$thisSnapshot;
return $thisShadow.ID;
}else{
$GLOBAL:shadow=$null;
$GLOBAL:snapshot=$null;
return $null;
}
}
Function rebuildVssLinks{
Function gatherSnapshots{
param(
$hostname=$env:computername,
$localLinkPrefix="C:\snapshots\$(try{(get-cluster).name}catch{"NoCluster"})\$env:computername",
$remoteLinkPrefix="\\Snapshots\FileServerClusters\$(try{(get-cluster).name}catch{"NoCluster"})\$env:computername"
)
# This variable holds the association between drive letters and shadow IDs
if(!($driveLettersExclusion)){$driveLettersExclusion="[C]\:"}
$driveLetterSnapshotsAssociation = Get-WmiObject Win32_Volume -Filter "DriveType=3" |?{$_.DriveLetter -ne $null -and $_.DriveLetter -notmatch $driveLettersExclusion}| select DriveLetter,Label, DeviceID | Sort DriveLetter;
# Set snapshot root directory variables if not exist
if(!($localSnapshotDirectory)){$localSnapshotDirectory="C:\Snapshots";}
if(!($localSnapshotDirectoryTransformed)){$localSnapshotDirectoryTransformed="\\$env:computername\C$\Snapshots"}
if(!($remoteSnapshotDirectory)){$remoteSnapshotDirectory="\\Snapshots\FileServerClusters"}
# Drive letter to labeling map (redundant and deprecated)
# $driveLettersAndLabels=get-volume |?{$_.DriveLetter -ne $null -and $_.DriveLetter -notmatch 'C'} | select DriveLetter,FileSystemLabel|sort -Property DriveLetter
# This variable holds all client accessible snapshots
$clientAccessibleSnapshots=Get-WmiObject -Class win32_shadowcopy|?{$_.ClientAccessible -eq $true -and $_.VolumeName -in $driveLetterSnapshotsAssociation.DeviceID}
$snapshotsCount=$clientAccessibleSnapshots.Count
$message+="There are $snapshotsCount on this $env:computername`r`n";
function transformLocalLink{
param(
$localLink,
$localSnapshotBase,
$transformedLocal
)
$commonDenominator=$localLink.Substring($localSnapshotBase.length,$localLink.length-$localSnapshotBase.length);
$transformedLocalLink=$transformedLocal+$commonDenominator;
return $transformedLocalLink;
}
function generateLink{
param(
$snapshotObject,
$snapshotToDriveLetter,
$linkPrefix
)
$volumeLetter=($snapshotToDriveLetter.DriveLetter[($snapshotToDriveLetter.DeviceID).IndexOf($snapshotObject.VolumeName)])[0];
$volumeLabel=$snapshotToDriveLetter.Label[($snapshotToDriveLetter.DriveLetter).IndexOf($volumeLetter)];
$label=(get-volume -DriveLetter $volumeLetter[0]).FileSystemLabel
$folderName="Volume_$volumeLetter`_$label";
if (!($label)){$folderName="Volume_$volumeLetter"};
$timeStamp=$snapshotObject.ConvertToDateTime($snapshotObject.InstallDate).ToString('yyyy-MM-dd_hh.mm.ss');
return "$linkPrefix\$folderName\$timeStamp";
}
# Initialize Array
if ($snapshotsCount -gt 1){
Write-Host "Processing $snapshotsCount snapshots..."
Write-Host "Gathering information on 1 of $snapshotsCount..."
$initSnapshot=$clientAccessibleSnapshots[0];
$GLOBAL:snapshots=@{}
$snapshots["targetPath"] = @{}; $snapshots["localLink"] = @{}; $snapshots["remoteLink"] = @{};
[string]$initLocalLink=generateLink -snapshotObject $initSnapshot -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $localLinkPrefix
[string]$initLocalLinkTransformed=transformLocalLink -localLink $initLocalLink -localSnapshotBase $localSnapshotDirectory -transformedLocal $localSnapshotDirectoryTransformed
[string]$initRemoteLink=generateLink -snapshotObject $initSnapshot -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $remoteLinkPrefix
$snapshots["targetPath"] = @("$($initSnapshot.DeviceObject)\");
$snapshots["localLink"] = @($initLocalLink)
$snapshots["transformedLocalLink"] = @($initLocalLinkTransformed);
$snapshots["remoteLink"] = @($initRemoteLink)
#$snapshots["installDate"] = @{}; $snapshots["installDate"] = @($initSnapshot.ConvertToDateTime($initSnapshot.InstallDate));
#$snapshots["timeStamp"] = @{}; $snapshots["timeStamp"] = @($initSnapshot.ConvertToDateTime($initSnapshot.InstallDate).ToString('yyyy-MM-dd_hh.mm.ss'));
#$snapshots["id"] = @{}; $snapshots["id"] = @({[void]($initSnapshot.ID -match "^{(.*)}$");$matches[1]}.Invoke());
#$snapshots["volumeLetter"] = @{}; $snapshots["volumeLetter"] = @($driveLetterSnapshotsAssociation.DriveLetter[($driveLetterSnapshotsAssociation.DeviceID).IndexOf($initSnapshot.VolumeName)])
# Load the rest of the values
for ($i=1; $i -lt $snapshotsCount; $i++){
Write-Host "Gathering information on $($i+1) of $snapshotsCount...";
$targetPath="$($clientAccessibleSnapshots[$i].DeviceObject)\";
$localLink="$(generateLink -snapshotObject $clientAccessibleSnapshots[$i] -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $localLinkPrefix)";
$transformedLocalLink=transformLocalLink -localLink $localLink -localSnapshotBase $localSnapshotDirectory -transformedLocal $localSnapshotDirectoryTransformed;
$remoteLink="$(generateLink -snapshotObject $clientAccessibleSnapshots[$i] -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $remoteLinkPrefix)";
$snapshots["targetPath"] += $targetPath;
$snapshots["localLink"] += $localLink;
$snapshots["transformedLocalLink"] += $transformedLocalLink;
$snapshots["remoteLink"] += $remoteLink;
}
}else{
$snapshots=@{}
$snapshots["targetPath"] = @{};$snapshots["localLink"] = @{};$snapshots["transformedLocalLink"]= @{};$snapshots["remoteLink"] = @{};
$thisLocalLink=generateLink -snapshotObject $clientAccessibleSnapshots -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $localLinkPrefix;
$localLinkObject=@($thisLocalLink);
$transformedLocalLinkObject=@(transformLocalLink -localLink $thisLocalLink -localSnapshotBase $localSnapshotDirectory -transformedLocal $localSnapshotDirectoryTransformed);
$snapshots["targetPath"] = @("$($clientAccessibleSnapshots.DeviceObject)\");
$snapshots["localLink"] = $localLinkObject
$snapshots["transformedLocalLink"] = $transformedLocalLinkObject;
$snapshots["remoteLink"] = @(generateLink -snapshotObject $clientAccessibleSnapshots -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $remoteLinkPrefix)
}
write-host "An object named `$`snapshots is now loaded with these properties: targetPath, localLink, transformedLocalLink, and remoteLink.";
return $snapshots;
}
Function rebuildLinks{
param($snapshotLinks)
$targets=$snapshotLinks.targetPath;
$localLinks=$snapshotLinks.localLink;
$transformedLocalLinks=$snapshotLinks.transformedLocalLink;
$remoteLinks=$snapshotLinks.remoteLink;
$linksCount=$localLinks.count
$results=@()
for ($i=0;$i -lt $linksCount; $i++){
$thisTarget=$targets[$i];
$thisLocalLink=$localLinks[$i];
$transformedLocalLink=$transformedLocalLinks[$i];
$thisRemoteLink=$remoteLinks[$i];
$remoteParentDirectory=split-path $thisRemoteLink -Parent
$localParentDirectory=split-path $thisLocalLink -Parent
New-Item -ItemType Directory -Force -Path $remoteParentDirectory | Out-Null;
New-Item -ItemType Directory -Force -Path $localParentDirectory | Out-Null;
write-host "Linking $thisLocalLink to $thisTarget.";
$voidOutput=cmd /c mklink /J $thisLocalLink $thisTarget;
write-host "Linking $thisRemoteLink to $transformedLocalLink.";
$voidOutput=cmd /c mklink /d $thisRemoteLink $transformedLocalLink;
$validRemoteLink=test-path "$thisRemoteLink"
if ($validRemoteLink){
$result="$thisRemoteLink validation: passed!";
$results+=,$result;
write-host $result;
}else{
$result="$thisRemoteLink validation: failed!";
$results+=,$result;
write-host $result;
}
}
return $results;
}
$message="";
$snapshotLinks=gatherSnapshots;
$message+=(rebuildLinks -snapshotLinks $snapshotLinks|Out-String);
return $message;
}
function proceed{
$startingMessage="===========================Process started on $dateStamp from host $thisComputer===========================`r`n";
write-host "$startingMessage";
importModuleFailoverClusters;
$GLOBAL:clusterName=(get-cluster).name
$GLOBAL:localSnapshotPath="$localSnapshotDirectory\$clusterName"
$GLOBAL:remoteSnapshotPath="$remoteSnapshotDirectory\$clusterName"
$GLOBAL:localLogFile=$localSnapshotPath+"\$env:computername-log.txt";
$GLOBAL:remoteLogFile=$remoteSnapshotPath+"\$env:computername-log.txt";
$proceedingMessages=$startingMessage;
if ($clusterName){
New-Item -ItemType Directory -Force -Path $remoteSnapshotPath | Out-Null;
New-Item -ItemType Directory -Force -Path $localSnapshotPath | Out-Null;
enableR2RSymbolicLinks;
if ((test-path $localSnapshotPath) -and (test-path $remoteSnapshotPath) -and ($localVolumes)){
# Creating new snapshots
$proceedingMessages+="New Snapshots:`r`n---------`r`n";
$localVolumes|%{
$GLOBAL:volumeLetter=$_[0];
$volumeDescription=((get-volume -DriveLetter $volumeLetter).FileSystemLabel)
if (!($volumeDescription)){
$GLOBAL:volumelabel="Volume_$volumeLetter";
}else{
$GLOBAL:volumelabel="Volume_$volumeLetter`_$volumeDescription";
}
write-host "Processing volume $volumelabel"
$localLinkPrefix="$localSnapshotPath\$hostname\$volumeLabel";
$transformedLocalLinkPrefix="\\$hostname\C$\Snapshots\$clusterName\$hostname\$volumeLabel"
$remoteLinkPrefix="$remoteSnapshotPath\$hostname\$volumeLabel"
if(checkDiskFree -volume $_){
$snapShotID=createNewSnapShot -targetVolume $_;
if($snapshotID){
$message=[string]$_+" "+$snapShotID
$proceedingMessages+="$message`r`n";
}else{
$message="$_ VSS Snapshot NOT taken due to an error.";
$proceedingMessages+="$message`r`n";
}
}else{
$message="$_ does NOT have sufficient disk space available for taking snapshots.";
$proceedingMessages+="$message`r`n";
}
} #end for-each volume in local volumes
$message=rebuildVssLinks
$proceedingMessages+="`r`nRemote Links:`r`n---------`r`n$message`r`n";
}else{
$message="Process is aborted due to missing items.";
$proceedingMessages+="$message`r`n";
}
$cleanupResult=cleanupSnapshots -daysOlderThan $retentionPeriod;
$proceedingMessages+=$cleanupResult
}else{
$message="This process is intended for taking snapshots of failover cluster nodes.`r`nAborting due to inability to detect cluster name.";
$proceedingMessages+="$message`r`n";
}
return $proceedingMessages;
}
$duration=[math]::round((measure-command {$results=proceed}).TotalMinutes,2);
$closingMessage="`r`n========================================Process has completed in $duration minutes=========================================";
$output=$results+$closingMessage;
write-host "Result:`r`n$output";
Set-Content $localLogFile $output; #This local log file shall contain results from this single host
Set-Content $remoteLogFile $output; #This remote log file shall contain results from multiple servers
Categories: