Powershell script to delete files not specified in a list

前提是你 提交于 2019-12-03 19:06:54

问题


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 Powershell?

Pseudo-code:

  • Read the text file line-by-line
  • Create a list of filenames
  • Recurse folder and its subfolders
  • If filename is not in list, delete it.

回答1:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/2009955/powershell-script-to-delete-files-not-specified-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!