Starting with your fist line
$filestobackup = Get-ChildItem D:\Documents\TestFiles -Recurse
This will return an array of file and directory objects (depending on contents of D:\Documents\TestFiles) These items need to be processed one by one.
The statements
$filename = ($filestobackup).BaseName $lasteditdatesource=($filestobackup).LastWriteTime
do not make any sense, except for one special case where there is only one file in the directory.
I'm assuming that you want to backup a directory structure, creating files that do not exist in destination directory and overriding files that do exist, but are older.
Here is code that I would use.
$SourceFolder = "D:\temp" $DestFolder = "D:\temp1" $SourceItems = Get-ChildItem $SourceFolder -Recurse # get all files and directories # First mirror the source directory structure to destination $SouceDirs = $SourceItems | Where-Object {$_.PSIsContainer -EQ $true} foreach ($dir in $SouceDirs) { $DestPath = $dir.FullName.Replace($SourceFolder,$DestFolder) if (!(Test-Path $DestPath)){ New-Item -ItemType Directory -Path $DestPath | Out-Null } } # Now you can try to copy files $SouceFiles = $SourceItems | Where-Object {$_.PSIsContainer -EQ $false} foreach ($file in $SouceFiles) { $DestPath = $file.FullName.Replace($SourceFolder,$DestFolder) if (!(Test-Path $DestPath)){ Copy-Item -Path $file.FullName -Destination $DestPath }else{ $DestFile = Get-Item $DestPath if ($DestFile.LastWriteTime -lt $file.LastWriteTime){ Copy-Item -Path $file.FullName -Destination $DestPath -Force } } }