1

I'm writing this script to backup data incrementally, but when I run it, it tries to find the source files in the directory that the script is running in, rather than the specified path.

$filestobackup = Get-ChildItem D:\Documents\TestFiles -Recurse $filename = ($filestobackup).BaseName $lasteditdatesource=($filestobackup).LastWriteTime $destfile = Get-ChildItem D:\Documents\FileServerBackup\ -Recurse if (!(Test-Path D:\Documents\FileServerBackup\$filename)) { Copy-Item $filestobackup -Destination $destfile -Verbose } elseif(($destfile).CreationTime -le ($filestobackup).LastWriteTime) { "$filestobackup will be copied to $destfile" } 

1 Answer 1

1

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 } } } 
Sign up to request clarification or add additional context in comments.

4 Comments

If it makes any difference, this is intended to run as a scheduled task regularly.
Hi David, the basic code above should be fine for a scheduled task. You can add reporting to a log file or event log, or more copy/sync options.
Why the out-null in the directory creation section?
The New-Item command returns a PSObject representing the new directory, Unless this is assigned to a variable or discarded (out-null) it will be written to output and make a mess.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.