IvoDijkgraaf
12/17/2014 - 9:57 AM

MirrorFolder

PowerShell: MirrorFolder

Function LogWrite
{
	Param ([string]$logString)

	Add-Content -Path $logFile -Value ($(get-date -f MM-dd-yyyy_HH_mm_ss) + ": " + $logString)
}

# Location of the Log File
$logFile = "C:\Logs\Copy.log"

$Source = 'D:\1'
$Destination = 'D:\2'

# Write to the Log File
LogWrite "Start Copy $Source to $Destination"
 
$SrcEntries = Get-ChildItem $Source -Recurse

ForEach($Src In $SrcEntries)
{
 $SrcPath = $Src.Fullname
 $DesPath = $SrcPath.Replace($Source, $Destination)
   
 #Check is source exist in dest
 if(test-Path $DesPath)
 {
  #if source was change 
  If(Compare-Object $SrcPath $DesPath) 
  {
   #then replace
   Copy-Item $SrcPath $DesPath -Force
   LogWrite "Replace $SrcPath to $DesPath"
  }
 }
 else
 {         
  #if dont exist then copy too
  Copy-Item $SrcPath $DesPath
  LogWrite "New item $SrcPath to $DesPath"
 }
}

$DesEntries = Get-ChildItem $Destination -Recurse
foreach($Des in $DesEntries)
{
 $DesPath = $Des.fullname
 $SrcPath = $DesPath.Replace($Destination, $Source)
   
 if((test-Path $SrcPath) -eq $false)
 {
  #if source dont exist then delete dest
  Remove-Item $DesPath
  LogWrite "Remove $DesPath"
 }
}