PowerShell脚本求助:复制新增文件并保留原目录结构
实现PowerShell复制新增文件并保留原目录结构
核心思路
通过筛选指定时间范围内的新增/修改文件,逐一构建对应目标路径以保留原目录结构,完成批量复制。以下是可直接复用的脚本方案:
基础版脚本(按时间筛选新增文件)
# 配置核心路径与筛选时间 $sourcePath = "C:\Your\Source\Folder" $targetPath = "C:\Your\Target\Folder" # 示例:筛选24小时内新增/修改的文件,可按需调整时间范围 $lastProcessTime = (Get-Date).AddHours(-24) # 获取符合条件的新增文件 $newFiles = Get-ChildItem -Path $sourcePath -Recurse -File | Where-Object { $_.LastWriteTime -gt $lastProcessTime } # 批量复制并保留目录结构 foreach ($file in $newFiles) { # 替换源路径为目标路径,生成对应文件的目标位置 $targetFilePath = $file.FullName.Replace($sourcePath, $targetPath) # 创建目标目录(若不存在则自动生成) $targetDir = Split-Path -Path $targetFilePath -Parent if (-not (Test-Path $targetDir)) { New-Item -Path $targetDir -ItemType Directory -Force | Out-Null } # 执行复制,-Force会覆盖目标已存在的同名文件 Copy-Item -Path $file.FullName -Destination $targetFilePath -Force }
进阶优化:记录上次处理时间(避免重复复制)
如果需要定期运行脚本,可将上次处理时间存入日志文件,确保每次只复制上次运行后新增的文件:
$sourcePath = "C:\Your\Source\Folder" $targetPath = "C:\Your\Target\Folder" $timeLogPath = "C:\Your\Log\LastProcessTime.txt" # 读取上次处理时间,首次运行默认取7天前 if (Test-Path $timeLogPath) { $lastProcessTime = Get-Content $timeLogPath | Get-Date } else { $lastProcessTime = (Get-Date).AddDays(-7) } # 获取新增文件并复制(同基础版逻辑) $newFiles = Get-ChildItem -Path $sourcePath -Recurse -File | Where-Object { $_.LastWriteTime -gt $lastProcessTime } foreach ($file in $newFiles) { $targetFilePath = $file.FullName.Replace($sourcePath, $targetPath) $targetDir = Split-Path -Path $targetFilePath -Parent if (-not (Test-Path $targetDir)) { New-Item -Path $targetDir -ItemType Directory -Force | Out-Null } Copy-Item -Path $file.FullName -Destination $targetFilePath -Force } # 更新处理时间日志 Get-Date | Set-Content -Path $timeLogPath
关键说明
-Recurse -File确保只遍历源目录下的所有文件(不含目录本身)Replace($sourcePath, $targetPath)精准保留原文件的相对目录结构-Force参数用于覆盖目标目录中已存在的同名文件,若不需要覆盖可移除该参数- 可通过添加
-Filter *.docx到Get-ChildItem中,筛选特定类型的文件
内容的提问来源于stack exchange,提问作者zjdrummond
相关产品推荐
相关产品推荐

