Powershell script to delete files not specified in a list

后端 未结 3 768
自闭症患者
自闭症患者 2020-12-25 08:46

I have a list of filenames in a text file like this:

f1.txt
f2
f3.jpg

How do I delete everything else from a folder except these files in P

相关标签:
3条回答
  • 2020-12-25 09:26

    If the files exist in the current folder then you can do this:

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

    This approach assumes each file is on a separate line. If the files exist in subfolders then I would go with Oisin's approach.

    0 讨论(0)
  • 2020-12-25 09:38

    actually this only seems to work for the first directory rather than recursing - my altered script recurses properly.

    $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
    
    0 讨论(0)
  • 2020-12-25 09:39

    Data:

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

    Code:

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

    Remove the -WhatIf switch if you are happy with your results. -WhatIf shows you what it would do (i.e. it will not delete)

    -Oisin

    0 讨论(0)
提交回复
热议问题