Powershell Get ChildItem查找脚本目录中的文件,而不是指定的路径

Powershell Get ChildItem查找脚本目录中的文件,而不是指定的路径,powershell,get-childitem,Powershell,Get Childitem,我写这个脚本是为了增量备份数据,但当我运行它时,它会尝试在脚本运行的目录中查找源文件,而不是在指定的路径中 $filestobackup = Get-ChildItem D:\Documents\TestFiles -Recurse $filename = ($filestobackup).BaseName $lasteditdatesource=($filestobackup).LastWriteTime $destfile = Get-ChildItem D:\Documents\FileS

我写这个脚本是为了增量备份数据,但当我运行它时,它会尝试在脚本运行的目录中查找源文件,而不是在指定的路径中

$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"
}

从你的第一句话开始

$filestobackup = Get-ChildItem D:\Documents\TestFiles -Recurse
这将返回一个文件和目录对象数组(取决于
D:\Documents\TestFiles
)这些项目需要逐个处理

声明

$filename = ($filestobackup).BaseName
$lasteditdatesource=($filestobackup).LastWriteTime
没有任何意义,除了目录中只有一个文件的特殊情况

我假设您要备份目录结构,创建目标目录中不存在的文件,并覆盖确实存在但较旧的文件

下面是我将使用的代码

$SourceFolder=“D:\temp”
$DestFolder=“D:\temp1”
$SourceItems=Get ChildItem$SourceFolder-Recurse#获取所有文件和目录
#首先将源目录结构镜像到目标目录
$soucdirs=$SourceItems |其中对象{$\ PSIsContainer-EQ$true}
foreach($soucdirs中的dir){
$DestPath=$dir.FullName.Replace($SourceFolder,$DestFolder)
如果(!(测试路径$DestPath)){
新项目-项目类型目录-路径$DestPath | Out Null
}
}
#现在您可以尝试复制文件
$SouceFiles=$SourceItems |其中对象{$\ PSIsContainer-EQ$false}
foreach($SouceFiles中的文件){
$DestPath=$file.FullName.Replace($SourceFolder,$DestFolder)
如果(!(测试路径$DestPath)){
复制项目-路径$file.FullName-目标$DestPath
}否则{
$DestFile=获取项目$DestPath
如果($DestFile.LastWriteTime-lt$file.LastWriteTime){
复制项目-路径$file.FullName-目标$DestPath-强制
}
}
}

如果有什么不同,这是为了定期作为计划任务运行。您好,David,上面的基本代码对于计划任务来说应该没问题。您可以将报告添加到日志文件、事件日志或更多复制/同步选项中。为什么在目录创建部分使用out null?命令
New Item
返回表示新目录的PSObject,除非将其分配给变量或丢弃(
out null
),否则它将写入输出并造成混乱。