Forum Discussion
adrian138
Jul 20, 2023Copper Contributor
Windows Powershell Copy-item only new Files
Hi, My Powershellscript copies SQL Dump Files from a Domainjoined SQL Server to a Workgroup Backupserver. This works fine. The Script now copies always all Backupfiles from the SQL Server t...
kevkelly
Jul 20, 2023MCT
Hi adrian138
One way that you could achieve this would be to use a log file that keeps track of a "last runtime" of your delta sync copy and then copying only files that have a creation/last modified time which is greater than the value written to your log file
Here's a sample PowerShell script to get you started:
$sourceDirectory = "C:\Path\to\source\directory"
$destinationDirectory = "C:\Path\to\destination\directory"
$logFile = "C:\Path\to\log\file.txt"
# Check if the log file exists and retrieve last run time
if (Test-Path -Path $logFile) {
$lastRunTime = Get-Date (Get-Content $logFile)
}
else {
$lastRunTime = [DateTime]::MinValue
}
# Get files from the source directory
$files = Get-ChildItem $sourceDirectory -File
# Filter only files that have been created or modified since the last run time
$newFiles = $files | Where-Object { $_.CreationTime -gt $lastRunTime -or $_.LastWriteTime -gt $lastRunTime }
# Copy new files to the destination directory
$newFiles | ForEach-Object {
$destinationPath = Join-Path -Path $destinationDirectory -ChildPath $_.Name
Copy-Item -Path $_.FullName -Destination $destinationPath
}
# Update the last run time in the log file
(Get-Date).ToString("yyyy-MM-dd HH:mm:ss") | Out-File -FilePath $logFile