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

如何用PowerShell移动除最新修改文件外的所有文件?

归档任务:PowerShell保留最新修改文件并移动其余文件到备份目录

我正在简化一项归档任务,卡在了关键环节:需要用PowerShell搜索指定文件夹,将除**最新修改(依据LastWriteTime)**之外的所有文件移动至备份文件夹。

找过相关解决方案,但现有方案要么只处理最旧文件,要么依赖特定命名规则,不符合需求。

需求场景示例

  • 源目录:E:\ProjectFolder1\EDLs\
    • File1.prproj(修改于6天前)
    • File2.prproj(修改于6小时前)
    • File3.prproj(修改于6秒前)
  • 目标效果:识别File3.prproj为最新文件,将其余文件移动至备份目录E:\Deep Storage\ProjectFolder1\EDLs\

我已经掌握其他操作步骤,但不知道如何通过PowerShell对比LastWriteTime实现这个需求,请问可行吗?


初始尝试代码

Get-ChildItem $sourceDir -Include $search -Recurse | Sort-Object LastWriteTime -Descending | Select-Object -Skip 1 | `
    foreach{ 
        $targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length); 
        New-Item -ItemType File -Path $targetFile -Force;  
        Move-Item $_.FullName -destination $targetFile -Force
    } 

可用的递归处理子目录代码

$sourceDir = "E:\Test1\EDLs\"
$targetDir = "E:\Deep Storage\Test1\EDLs\"
$search = "*.prproj"

Get-ChildItem $sourceDir -Recurse -Directory | ForEach-Object {
    $files = $_ | Get-ChildItem -File -Filter $search
    if($files.Count -lt 2) {
        return
    }

    $newPath = Join-Path $targetDir -ChildPath $_.FullName.Substring($sourceDir.Length)
    $null = New-Item $newPath -ItemType Directory -Force
    $files | Sort-Object LastWriteTime -Descending | Select-Object -Skip 1 |
        Move-Item -Destination $newPath -Verbose -WhatIf
    }

适配单层级目录的代码

$sourceDir = "E:\Projects\Current\EDLs"
$targetDir = "E:\Deep Storage\Projects\Current\EDLs"
$search = "*.prproj"

Get-ChildItem $sourceDir -Directory | ForEach-Object {
# 仅搜索当前目录下一级的文件
$files = Get-ChildItem $sourceDir -Filter *.prproj
# 至少存在2个文件时执行操作
if($files.Count -ge 2) {
    # 无需创建新文件夹,直接按逻辑排序并跳过最新文件
    $files | Sort-Object LastWriteTime -Descending | Select-Object -Skip 1 |
        # 移动文件到目标目录
        Move-Item -Destination $targetDir
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:35:26