PowerShell递归复制文件 如何实现单文件复制后暂停10秒
PowerShell脚本修改方案
核心改动逻辑:
- 替换原脚本一次性批量递归复制的逻辑,改为逐个遍历源路径文件执行复制,自动保留原目录结构
- 单个文件复制完成后强制暂停10秒,确保每个复制后的文件生成独立可区分的创建时间戳
- 修复原脚本日志路径拼接、编码等潜在问题,避免目标路径末尾不带路径分隔符时日志保存位置错误、中文乱码等问题
修改后的完整脚本如下:
$Logfile = 'File_detaisl.csv' $SourcePath = Read-Host 'Enter the full path containing the files to copy' "" "" $TargetPath = Read-Host 'Enter the destination full path to copy the files' "" # 初始化目标根目录(不存在则自动创建) if (-not (Test-Path -Path $TargetPath)) { New-Item -Path $TargetPath -ItemType Directory -Force | Out-Null } # 遍历源路径所有文件逐个复制 Get-ChildItem -Path $SourcePath -Recurse -Force -File | ForEach-Object { # 计算文件相对路径,保留源目录层级结构 $relativePath = $_.FullName.Substring($SourcePath.TrimEnd('\','/').Length) $destFilePath = Join-Path -Path $TargetPath -ChildPath $relativePath $destDir = Split-Path -Path $destFilePath -Parent # 目标子目录不存在则提前创建 if (-not (Test-Path -Path $destDir)) { New-Item -Path $destDir -ItemType Directory -Force | Out-Null } # 执行单文件复制 Copy-Item -Path $_.FullName -Destination $destFilePath -Force Write-Host "已复制完成:$($_.Name),等待10秒后处理下一个文件" # 暂停10秒 Start-Sleep -Seconds 10 } # 生成文件明细日志 $logFullPath = Join-Path -Path $TargetPath -ChildPath $Logfile Get-ChildItem -Path $TargetPath -Recurse -Force -File | Where-Object { $_.FullName -ne $logFullPath } | # 排除日志文件本身,避免冗余记录 Select-Object Name,DirectoryName,Length,CreationTime,LastWriteTime, @{N='MD5 Hash';E={(Get-FileHash -Algorithm MD5 $_.FullName).Hash}}, @{N='SHA-1 Hash';E={(Get-FileHash -Algorithm SHA1 $_.FullName).Hash}} | Sort-Object -Property Name,DirectoryName | Export-Csv -Path $logFullPath -NoTypeInformation -Encoding UTF8
补充说明
- 脚本运行时会在控制台输出当前复制进度,方便查看执行状态
- 如果需要调整等待间隔,直接修改
Start-Sleep -Seconds 10中的数值即可,单位为秒 - 导出日志默认使用UTF8编码,可避免中文文件名、路径出现乱码问题
内容的提问来源于stack exchange,提问作者PF6004
相关产品推荐
相关产品推荐

