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"
}
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
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.