#Import PVS PowerShell Module
#This script file is intended to provide an example script of how vDisk replication can be performed.
#This script will get secondary site servers for each Farm defined by a Master Server

#This script was created by Rob Zylowski Citrix CCS with help from many folks
#It should be used as an example of how to perform PVS Disk replication.
#This script will interrogate defined PVS master Servers to compile a list of stores and store paths.
#
#Although every effort has been made to ensure that these sample scripts work properly, 
#Citrix disclaims any responsibility for any and all liability or responsibility for any 
#damages that may result from using these scripts. 
#The sample scripts are provided to you as is, with no warranty or guarantees.
#

#Version 2.0.2 modified 7-5-2018

try{
    Import-Module 'C:\Program Files\Citrix\Provisioning Services console\Citrix.PVS.SnapIn.dll' -ErrorAction Stop
} catch {
    Write-Host "PVS PowerShell Snap-In Not Found" -BackgroundColor Black -ForegroundColor Red
    $msg = "PVS PowerShell Snap-In Not Found on $env:computername.  Script terminated."
    Write-EventLog -LogName Application -Source $logSource -EventId 2 -EntryType Error -Message $msg -Category 0
    exit
}


function Get-ScriptDirectory
#This gets the current directlry which we use to store the text data files
{
 $Invocation = (Get-Variable MyInvocation -Scope 1).Value
 Split-Path $Invocation.MyCommand.Path
}

$ScriptSource = Get-ScriptDirectory

$Masters = Get-Content "$ScriptSource\..\config\masters.txt"
if ($Masters.count -gt 1)
{
	$FirstMaster = $Masters[0].ToLower()
}
else
{
	$FirstMaster = $Masters
}

Write-Host "First Master Found - Looking for vhd and vhdx files on Master $FirstMaster"
$ReplFiles="$ScriptSource\..\Config\ReplFiles.txt"
if (Test-Path $ReplFiles){del $ReplFiles}
#get Stores for Master

Set-PvsConnection -Server $FirstMaster -ErrorAction SilentlyContinue

$rowoutput=""
Write-Host "Getting PVS Stores"
$MasterStoresArray = Get-PvsStore
foreach($Store in $MasterStoresArray)
{
	
	$ServerStorePathOrig =  $Store.Path
	$StoreName = $store.StoreName
	if ($ServerStorePathOrig.StartsWith("\\"))
	{
		$StorePath = $ServerStorePathOrig
	}
	else
	{
		Write-Host "Processing Store $StoreName"
		$ServerStorePath = $ServerStorePathOrig.Replace(":", "$")
		$StorePath = "\\" +$FirstMaster + "\" + $ServerStorePath
	}
	$storeFiles = Get-ChildItem -File -Path "$StorePath\*" -Include *.vhd, *.vhdx , *.avhd, *.avhdx
	foreach ($fileNameFull in $storeFiles)
	{
		$fileName = $fileNameFull | Select -exp Name
		Write-Host "Found File $fileName"
		$rowoutput = "$StoreName;$fileName"
		$rowoutput | Out-File -LiteralPath $ReplFiles -Encoding ASCII -Append
	}
}

Sleep 5



