Powershell脚本删除列表中未指定的文件 [英] Powershell script to delete files not specified in a list

查看:214
本文介绍了Powershell脚本删除列表中未指定的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

f1.txt
f2
f3.jpg

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

How do I delete everything else from a folder except these files in 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向您显示会做什么(即不会删除)

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

这篇关于Powershell脚本删除列表中未指定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆