用于删除列表中未指定的文件的 Powershell 脚本
-
18-09-2019 - |
题
我在文本文件中有一个文件名列表,如下所示:
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
向你展示它是什么 会 做(即它不会删除)
-奥辛
其他提示
如果文件存在于当前文件夹中,那么您可以执行以下操作:
Get-ChildItem -exclude (gc exclusions.txt) | Remove-Item -whatif
此方法假设每个文件位于单独的行上。如果文件存在于子文件夹中,那么我会采用 Oisin 的方法。
实际上,这似乎只适用于第一个目录,而不是递归 - 我更改的脚本可以正确递归。
$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
不隶属于 StackOverflow