14

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

f1.txt
f2
f3.jpg

除了Powershell中的这些文件之外,如何从文件夹中删除所有其他内容?

伪代码:

  • 逐行读取文本文件
  • 创建文件名列表
  • 递归文件夹及其子文件夹
  • 如果文件名不在列表中,请将其删除。
4

3 回答 3

21

数据:

-- 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告诉你它做什么(即它不会删除)

-Oisin

于 2010-01-06T00:01:53.270 回答
6

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

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

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

于 2010-01-06T00:22:09.650 回答
1

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

$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
于 2010-03-03T14:29:02.763 回答