Windows Powershell Copy-item only new Files

Copper Contributor



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 to the Backup Server. I want only the Delta (new Backup Files) to be copied to the Backupserver. How can i do this?


Thanks alot, 





#(get-credential).Password | ConvertFrom-SecureString -key (get-content C:\scripts\aes.key) | set-content "c:\scripts\password.txt"
$password = Get-Content C:\scripts\password.txt | ConvertTo-SecureString -Key (Get-Content c:\scripts\aes.key)
$cred = New-Object System.Management.Automation.PSCredential("\admin", $password) 
$session = new-pssession -computername -credential $cred
$Source = "E:\Backup\"  
$items = Get-ChildItem $Source -Force
ForEach ($item in $items)
$destinationFile = $Destination+$item.FullName
if (-not (test-path $destinationFile))
Copy-Item -Path $item.FullName -Destination $Destination -ToSession $Session -Recurse -Force -Confirm:$false








1 Reply

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