代码之家  ›  专栏  ›  技术社区  ›  Mrchief

用于删除列表中未指定的文件的PowerShell脚本

  •  11
  • Mrchief  · 技术社区  · 15 年前

    我在这样的文本文件中有一个文件名列表:

    f1.txt
    f2
    f3.jpg
    

    如何从PowerShell中的文件夹中删除除这些文件以外的所有其他文件?

    伪代码:

    • 逐行读取文本文件
    • 创建文件名列表
    • 递归文件夹及其子文件夹
    • 如果文件名不在列表中,请将其删除。
    3 回复  |  直到 9 年前
        1
  •  15
  •   x0n    11 年前

    数据:

    -- begin exclusions.txt --
    a.txt
    b.txt
    c.txt
    -- end --
    

    代码:

    # read all exclusions into a string array
    $exclusions = Get-Content .\exclusions.txt
    
    dir -rec *.* | Where-Object {
       $exclusions -notcontains $_.name } | `
       Remove-Item -WhatIf
    

    移除 -WhatIf 如果您对结果满意,请切换。 - WHATIF 给你看什么 do(即不会删除)

    -奥辛

        2
  •  6
  •   Keith Hill    15 年前

    如果文件存在于当前文件夹中,则可以执行以下操作:

    Get-ChildItem -exclude (gc exclusions.txt) | Remove-Item -whatif
    

    这种方法假定每个文件都在单独的行上。如果文件存在于子文件夹中,那么我将使用Oisin的方法。

        3
  •  1
  •   user285386    14 年前

    实际上,这似乎只适用于第一个目录,而不是递归——我修改过的脚本会正确地递归。

    $exclusions = Get-Content .\exclusions.txt
    
    dir -rec | where-object {-not($exclusions -contains [io.path]::GetFileName($_))} | `  
    where-object {-not($_ -is [system.IO.directoryInfo])} | remove-item -whatif