<# Daily-VSS-Snapshot-Windows-Standalone-FileServer.ps1

Functions:
1. Dynamically detect all volumes on local machine
2. Take snapshots of each locally mounted volume (including iSCSI LUNs) and mount them onto C:\Snapshots\$hostname\$volumeLabel\$snapshotTimeStamp
3. 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="[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 variable
$localSnapshotDirectory="C:\Snapshots"

# Set Retention Period
$retentionPeriod=30;

# 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 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 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 -gt $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 $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')"        
    )

    # Create snapshot directory
    New-Item -ItemType Directory -Force -Path "$localSnapshotPath\$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 /J $localShapshot $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: $localShapshot"

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

function proceed{
    $GLOBAL:localSnapshotPath="$localSnapshotDirectory"
    New-Item -ItemType Directory -Force -Path $localSnapshotPath | Out-Null;
    enableR2RSymbolicLinks;
        
    removeSnapshots -daysOlderThan $retentionPeriod;
    
    if ((get-item $localSnapshotPath) -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')";
        
        if(checkDiskFree -volume $_){
            createNewSnapShot -targetVolume $_ -label $volumeLabel -localShapshot $snapshotLink;
            }else{"Volume $_ does NOT have sufficient disk space available for taking snapshots."}        
        }
    
    }else{"Program aborted due to insufficient local volumes."}    
}

proceed;
<# VSS-Snapshots-on-Microsoft-File-Server-Clusters.ps1

Functions:
1. Remove all previous snapshots that are older than retention period
2. Dynamically detect all volumes on local machine
3. Dynamically take snapshots of each volume and mount them into C:\snapshots\$hostname\$volumeLabel\$snapshotTimeStamp (i.e. \\FILESHERVER01\Snapshots\HOSTNAME007\VOLUMELABEL007)

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 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="[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 variable
$localSnapshotDirectory="C:\Snapshots"
$remoteSnapshotDirectory="\\Snapshots\FileServerClusters"

# Set Retention Period
$retentionPeriod=30;

# 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 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 removeSnapshots{
[cmdletbinding()]
param(
[int]$retentionPeriod=30
)

# Remove links older than X days
function removeLinks{
[cmdletbinding()]
param(
[string]$snapshotRootDirectory="C:\Snapshots",
[int]$retentionPeriod=30
)

# Remove dead links
$allSymlinks=Get-ChildItem $snapshotRootDirectory -Recurse -Depth 3 -ErrorAction SilentlyContinue|Where-Object {($_.Attributes -match "ReparsePoint")}
$allSymlinks|%{ if(!(Test-Path "$($_.Fullname)\*")){
(Get-Item $_.Fullname).Delete();
Write-Host "Removed dead link: $_";
}
}

# Remove parent directory of dead links (empty directories)
$parentDirectories=Get-ChildItem $snapshotRootDirectory\*\* -ErrorAction SilentlyContinue
$parentDirectories|%{
$directoryChildren = Get-ChildItem $_.FullName
if ($directoryChildren.count -eq 0){
(Get-Item $_.Fullname).Delete();
Write-Host "Removed empty folder: $($_.Fullname)";
}}

# Remove remaining expired links
$remainingSymlinks=Get-ChildItem $snapshotRootDirectory -Recurse -Depth 3 -ErrorAction SilentlyContinue|Where-Object {($_.Attributes -match "ReparsePoint")}
foreach ($link in $remainingSymlinks){
$creationTime=$link.CreationTime
$thisSymlink=$link.FullName
$removeSymlink=$creationTime -lt (Get-Date).AddDays(-$retentionPeriod)

# 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 -Class win32_shadowcopy|?{$_.ClientAccessible -eq $true}
#$driveLetterSnapshotsAssociation = Get-WmiObject Win32_Volume -Filter "DriveType=3" |?{$_.DriveLetter -ne $null}| select DriveLetter,Label, DeviceID | Sort DriveLetter;

$allSnapshots | ForEach-Object {
$snapshotDate = $_.InstallDate
$snapshotID = $_.ID
#$snapshotID = {[void]($_.ID -match "^{(.*)}$");$matches[1]}.Invoke()
#$volumePath = "$($driveLetterSnapshotsAssociation.DriveLetter[($driveLetterSnapshotsAssociation.DeviceID).IndexOf($_.VolumeName)]):"
$snapshotDateTimeValue = [management.managementDateTimeConverter]::ToDateTime($snapshotDate)
$thisClientAccessibleValue = $_.ClientAccessible
$currentDate = Get-Date
$timeSpan = New-TimeSpan $snapshotDateTimeValue $currentDate
$days = $timeSpan.Days

If ($days -gt $retentionPeriod) {
#$_.Delete() # does nothing
#invoke-expression "vssadmin delete shadows /for=$volumePath /shadow=$snapshotID /quiet" # doesn't work, must invoke from cmd.exe
cmd.exe /c vssadmin delete shadows /Shadow=$snapshotID /quiet
"$snapshotID with date stamp of $snapshotDate has been DELETED as it's older than $retentionPeriod days."
} else{
"$snapshotID with date stamp of $snapshotDate has NOT been deleted as it's newer than $retentionPeriod days."
}
}
}

removeLinks -snapshotRootDirectory $remoteSnapshotPath -retentionPeriod $retentionPeriod
removeLinks -snapshotRootDirectory $localSnapshotPath -retentionPeriod $retentionPeriod
deleteOldSnapshots -retentionPeriod $retentionPeriod
}

function createNewSnapshot{
[cmdletbinding()]
param(
[string]$targetVolume="C:\",
[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 -like "*\")){$targetVolume+="\"}

#write-host "please check these links:`nlocalSnapshotPath: $localSnapshotPath`ntransformedLocalPath: $transformedLocalPath`nremoteLink: $remoteLink"

# 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 };
$shadowTimeStamp = $thisShadow.ConvertToDateTime($thisShadow.InstallDate).ToString('yyyy-MM-dd_hh.mm.ss');
$thisShadowPath = $thisShadow.DeviceObject + "\";

$localShapshot="$localLinkPrefix\$shadowTimeStamp";
$remoteLink="$remoteLinkPrefix\$shadowTimeStamp";
$transformedLocal="$transformedLocalLinkPrefix\$shadowTimeStamp";

# Create links toward this snapshot
cmd /c mklink /J $localShapshot $thisShadowPath;
cmd /c mklink /d $remoteLink $transformedLocal;

<# 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.
#>
"Snapshot of $targetVolume has been made and it's accessible at this path: $remoteLink"

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

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
$driveLetterSnapshotsAssociation = Get-WmiObject Win32_Volume -Filter "DriveType=3" |?{$_.DriveLetter -ne $null}| select DriveLetter,Label, DeviceID | Sort DriveLetter;

# 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}
$snapshotsCount=$clientAccessibleSnapshots.Count

function generateLink{
param(
$snapshotObject=(Get-WmiObject -Class win32_shadowcopy|?{$_.ClientAccessible -eq $true})[0],
$snapshotToDriveLetter=(Get-WmiObject Win32_Volume -Filter "DriveType=3" |?{$_.DriveLetter -ne $null}| select DriveLetter,Label, DeviceID | Sort DriveLetter),
$linkPrefix="c:\snapshots\$(try{(get-cluster).name}catch{"NoCluster"})\$env:computername"
)
$volumeLetter=($snapshotToDriveLetter.DriveLetter[($snapshotToDriveLetter.DeviceID).IndexOf($snapshotObject.VolumeName)])[0];
$volumeLabel=$snapshotToDriveLetter.Label[($snapshotToDriveLetter.DriveLetter).IndexOf($volumeLetter)];
$folderName="Volume_$volumeLetter`_$((get-volume -DriveLetter $volumeLetter).FileSystemLabel)";
if (!($folderName)){$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 snapshot..."
Write-Host "Gathering information on 1 of $snapshotsCount..."
$initSnapshot=$clientAccessibleSnapshots[0];

$GLOBAL:snapshots=@{}
$snapshots["targetPath"] = @{}; $snapshots["localLink"] = @{}; $snapshots["remoteLink"] = @{};
$snapshots["targetPath"] = @("$($initSnapshot.DeviceObject)");
$snapshots["localLink"] = @("$(generateLink -snapshotObject $initSnapshot -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $localLinkPrefix)")
$snapshots["remoteLink"] = @("$(generateLink -snapshotObject $initSnapshot -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $remoteLinkPrefix)")
#$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 2; $i++){
for ($i=1; $i -lt $snapshotsCount; $i++){
Write-Host "Gathering information on $($i+1) of $snapshotsCount..."
$snapshots["targetPath"] += "$($clientAccessibleSnapshots[$i].DeviceObject)";
$snapshots["localLink"] += "$(generateLink -snapshotObject $clientAccessibleSnapshots[$i] -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $localLinkPrefix)";
$snapshots["remoteLink"] += "$(generateLink -snapshotObject $clientAccessibleSnapshots[$i] -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $remoteLinkPrefix)";
}
}else{
$snapshots=@{}
$snapshots["targetPath"] = @{}; $snapshots["targetPath"] = @($clientAccessibleSnapshots.DeviceObject);
$snapshots["localLink"] = @{}; $snapshots["localLink"] = @(generateLink -snapshotObject $clientAccessibleSnapshots -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $localLinkPrefix)
$snapshots["remoteLink"] = @{}; $snapshots["remoteLink"] = @(generateLink -snapshotObject $clientAccessibleSnapshots -snapshotToDriveLetter $driveLetterSnapshotsAssociation -linkPrefix $remoteLinkPrefix)
}
write-host "An object named `$`snapshots is now loaded with these properties: targetPath, localLink, and remoteLink.";
return $snapshots;
}

Function rebuildLinks{
param($snapshotLinks=(gatherSnapshots))
$targets=$snapshotLinks.targetPath;
$localLinks=$snapshotLinks.localLink;
$remoteLinks=$snapshotLinks.remoteLink;

for ($i=0;$i -lt $localLinks.count; $i++){
$thisLocalLink="$($localLinks[$i])\";
$validLocalLink=test-path "$thisLocalLink*";
if(!($validLocalLink)){
$thisTarget="$($targets[$i])\";
write-host "validate this target $thisTarget.";
cmd /c mklink /J $thisLocalLink $thisTarget;
write-host "$thisLocalLink has been regenerated.";
}

$thisRemoteLink=$remoteLinks[$i];
write-host "validate this remote link $thisRemoteLink.";
$validRemoteLink=test-path "$thisRemoteLink\*"
if(!($validRemoteLink)){
cmd /c mklink /d $thisRemoteLink $thisLocalLink;
write-host "$thisRemoteLink has been regenerated.";
}

}
}

rebuildLinks;
}

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

if ($clusterName){
New-Item -ItemType Directory -Force -Path $remoteSnapshotPath | Out-Null;
New-Item -ItemType Directory -Force -Path $localSnapshotPath | Out-Null;
enableR2RSymbolicLinks;
removeSnapshots -daysOlderThan $retentionPeriod;
rebuildVssLinks;

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

if(checkDiskFree -volume $_){
createNewSnapShot -targetVolume $_ -label $volumeLabel -localLinkPrefix $localLinkPrefix -transformedLocalLinkPrefix $transformedLocalLinkPrefix -remoteLinkPrefix $remoteLinkPrefix;
}else{"Volume $_ does NOT have sufficient disk space available for taking snapshots."}
}
}else{"Program aborted due to missing items."}
} else{Write-Host "unable to import FailoverCluster Module"}
}

proceed;
<# Daily-VSS-Snapshot-Windows-Standalone-FileServer.ps1

Functions:
1. Dynamically detect all volumes on local machine
2. Take snapshots of each locally mounted volume (including iSCSI LUNs) and mount them onto C:\Snapshots\$hostname\$volumeLabel\$snapshotTimeStamp
3. 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="[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 variable
$localSnapshotDirectory="C:\Snapshots"

# Set Retention Period
$retentionPeriod=30;

# 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 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 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 -gt $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 $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')"
)

# Create snapshot directory
New-Item -ItemType Directory -Force -Path "$localSnapshotPath\$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 /J $localShapshot $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: $localShapshot"

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

function proceed{
$GLOBAL:localSnapshotPath="$localSnapshotDirectory"
New-Item -ItemType Directory -Force -Path $localSnapshotPath | Out-Null;
enableR2RSymbolicLinks;

removeSnapshots -daysOlderThan $retentionPeriod;

if ((get-item $localSnapshotPath) -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')";

if(checkDiskFree -volume $_){
createNewSnapShot -targetVolume $_ -label $volumeLabel -localShapshot $snapshotLink;
}else{"Volume $_ does NOT have sufficient disk space available for taking snapshots."}
}

}else{"Program aborted due to insufficient local volumes."}
}

proceed;