PowerShell脚本删除列表中的
没有指定文件,我有一个文件名列表在这样的文本文件:PowerShell脚本删除列表中的
f1.txt
f2
f3.jpg
如何删除一个文件夹中的一切,除了在PowerShell中这些文件?
伪代码:
- 阅读文本文件中的行由行
- 创建的文件名列表
- 递归文件夹及其子文件夹
- 如果文件名不是在列表中,删除它。
数据:
-- 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(即它不会删除)
-Oisin
如果在当前文件夹中的文件,那么你可以这样做:
Get-ChildItem -exclude (gc exclusions.txt) | Remove-Item -whatif
这种方法假设每个文件都在一个单独的行上。如果这些文件存在于子文件夹中,那么我会采用Oisin的方法。
是的,文件分开。感谢您的答案。 如果父位置具有子文件夹,我得到一个提示说“在该项目Microsoft.PowerShell.Core \ FileSystem的:: >有孩子和Recurse参数没有指定是,如果继续,所有的孩子将与删除项目,你确定要继续吗?“可能添加-recurse开关将修复它。 Oisin的方法不会导致此提示。 – Mrchief 2010-01-06 16:00:05
如果子目录都参与,那么你做*不*想用我的方法,你不希望使用-r否则会删除整个文件夹。 – 2010-01-06 16:22:44
其实这似乎只为第一个目录的工作,而不是在递归 - 我改变剧本递归正常。
$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
我用$ _。FullName.ToLower()代替[io.path] ::用GetFileName($ _),并在我的排除列表中使用的全路径名,以获得递归工作。 – toxaq 2011-10-06 09:44:31
我喜欢它。但是,为什么不使用-notcontains? – 2010-01-06 01:32:38
谢谢。这对我来说非常合适。正如Mike所建议的那样,我尝试使用-notcontains,结果是一样的。 – Mrchief 2010-01-06 16:01:29
我讨厌-notcontains。不,只是在开玩笑。是的,这是有史以来。 – x0n 2010-01-07 00:15:42