You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求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 参数复制时自动覆盖同名文件,无需确认

使用注意事项

  1. 替换脚本中的 D:\Source 和 F:\destination 为你的实际路径
  2. 确保运行脚本的账号拥有源目录的读取权限和目标目录的写入权限
  3. 如果需要处理目录而非文件,去掉脚本中排除目录的参数即可(比如PowerShell去掉 -File,批处理去掉 /a-d)

内容的提问来源于stack exchange,提问作者Kasra21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:05:43