001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
<# 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