求Windows 10中复制最后修改对象的脚本
复制指定目录下最后修改的文件到目标路径
方案1:PowerShell脚本(推荐)
PowerShell语法直观,处理文件属性更灵活,适合这类需求:
# 配置源目录和目标路径 $sourceDir = "D:\Source" $targetDir = "F:\destination" # 自动创建目标目录(不存在时) if (-not (Test-Path -Path $targetDir)) { New-Item -ItemType Directory -Path $targetDir | Out-Null } # 获取目录下最新修改的文件(仅文件,排除子目录) $latestFile = Get-ChildItem -Path $sourceDir -File | Sort-Object LastWriteTime -Descending | Select-Object -First 1 # 执行复制操作 if ($latestFile) { Copy-Item -Path $latestFile.FullName -Destination $targetDir -Force Write-Host "已完成复制:$($latestFile.Name) → $targetDir" } else { Write-Host "错误:源目录中未找到任何文件" }
关键说明:
-File参数确保只处理文件,不会选中目录Sort-Object LastWriteTime -Descending按修改日期从新到旧排序-Force参数会覆盖目标路径中已存在的同名文件- 如果需要包含子目录里的文件,给
Get-ChildItem加上-Recurse参数
方案2:批处理脚本(CMD环境)
如果需要在纯CMD环境运行,用批处理实现:
@echo off setlocal enabledelayedexpansion :: 配置路径 set "sourceDir=D:\Source" set "targetDir=F:\destination" :: 创建目标目录(不存在时) if not exist "%targetDir%" mkdir "%targetDir%" :: 遍历源目录,按修改时间倒序取第一个文件 for /f "delims=" %%a in ('dir /b /o-d /a-d "%sourceDir%"') do ( set "latestFile=%%a" goto :copyAction ) :copyAction if defined latestFile ( copy "%sourceDir%\!latestFile!" "%targetDir%" /y echo 已完成复制:!latestFile! → %targetDir% ) else ( echo 错误:源目录中未找到任何文件 ) endlocal
关键说明:
dir /o-d按修改时间从新到旧排序,/a-d排除目录,/b仅显示文件名setlocal enabledelayedexpansion确保循环内变量能正确取值/y参数复制时自动覆盖同名文件,无需确认
使用注意事项
- 替换脚本中的
D:\Source和F:\destination为你的实际路径 - 确保运行脚本的账号拥有源目录的读取权限和目标目录的写入权限
- 如果需要处理目录而非文件,去掉脚本中排除目录的参数即可(比如PowerShell去掉
-File,批处理去掉/a-d)
内容的提问来源于stack exchange,提问作者Kasra21
相关产品推荐
相关产品推荐

