<# Sync-VipClouds.ps1 Mirrors \\server\share to C:\vipclouds at user logon. Creates logs in %ProgramData%\vip_sync\logs\YYYYMMDD.txt #> #region Config $Source = '\\mios-app22\DomainResources\vip_sync' # <-- change if needed $Destination = 'C:\vipclouds' $DoMirror = $true # $true = /MIR (delete extras in dest). $false = /E (no deletions) $Excludes = @('*.tmp','*.bak','.DS_Store','Thumbs.db') # optional patterns $MaxRetries = 12 # ~2 minutes total with default wait $WaitSeconds = 10 #endregion #region Prep + Logging $LogRoot = Join-Path $env:ProgramData 'vip_sync\logs' $null = New-Item -ItemType Directory -Path $LogRoot -Force -ErrorAction SilentlyContinue $LogFile = Join-Path $LogRoot "$(Get-Date -Format 'yyyyMMdd').txt" Function Write-Log($msg) { $line = "[{0}] {1}" -f (Get-Date -Format 'HH:mm:ss'), $msg Add-Content -Path $LogFile -Value $line } Write-Log "==== Logon sync start. User=$env:USERNAME Computer=$env:COMPUTERNAME ====" Write-Log "Source=$Source Dest=$Destination Mirror=$DoMirror" #endregion #region Reachability + Dest ensure # Wait for network + share reachability $attempt = 0 while ($attempt -lt $MaxRetries) { if (Test-Path $Source) { break } $attempt++ Write-Log "Source not reachable (attempt $attempt/$MaxRetries). Sleeping ${WaitSeconds}s…" Start-Sleep -Seconds $WaitSeconds } if (-not (Test-Path $Source)) { Write-Log "ABORT: Source still unreachable after retries." exit 0 # don't block logon } # Ensure destination exists if (-not (Test-Path $Destination)) { try { New-Item -ItemType Directory -Path $Destination -Force | Out-Null Write-Log "Created destination folder: $Destination" } catch { Write-Log "ABORT: Failed to create $Destination : $($_.Exception.Message)" exit 0 } } #endregion #region Build robocopy args $modeSwitches = if ($DoMirror) { '/MIR' } else { '/E' } # /Z = restartable, /FFT = tolerate FAT time granularity, /R:2 /W:5 = quick retries, # /XO = skip older, /COPY:DAT = data+attrs+timestamps, /DCOPY:DAT = dir metadata $common = @( $Source, $Destination, $modeSwitches, '/Z', '/FFT', '/R:2', '/W:5', '/COPY:DAT', '/DCOPY:DAT', '/NP', '/NFL', '/NDL' ) # Exclusions $excludeArgs = @() if ($Excludes.Count -gt 0) { $excludeArgs += @('/XF'); $excludeArgs += $Excludes } # Log to file as well $logArg = @('/LOG+:' + $LogFile) $robocopyArgs = $common + $excludeArgs + $logArg #endregion #region Run robocopy Write-Log "Running: robocopy $($robocopyArgs -join ' ')" $start = Get-Date $rc = (Start-Process -FilePath 'robocopy.exe' -ArgumentList $robocopyArgs -Wait -PassThru).ExitCode $elapsed = (Get-Date) - $start Write-Log "Robocopy exit code: $rc Elapsed: {0:mm\:ss}" -f $elapsed # Robocopy success codes: 0,1,2,3,5,6,7 if ($rc -in 0,1,2,3,5,6,7) { Write-Log "Sync OK." exit 0 } else { Write-Log "Sync FAILED with code $rc. See robocopy docs for code meaning." exit 0 # still don’t block logon } #endregion