如何使用PowerShell删除与正则表达式匹配的文件夹中的文件? [英] How can one delete files in a folder matching a regular expression using PowerShell?

查看:326
本文介绍了如何使用PowerShell删除与正则表达式匹配的文件夹中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Windows计算机上许多不需要的文件的文件名的共同特征.如何使用单个正则表达式 PowerShell命令从给定的文件夹或文件夹层次结构中删除所有这些文件?

I know a common characteristic of the file names of a number of unwanted files on my Windows computer. How can I remove all of these files from a given folder or folder hierarchy with a single regular expression PowerShell command?

推荐答案

您可以通过Get-ChildItem命令通过一个接受RegEx模式的Where-Object过滤器进行传递,然后将其传递给Remove-Item.我认为,与使用Select-String相比,它将为您带来更快,更好的结果.像这样的命令:

You can pipe a Get-ChildItem command through a Where-Object filter that accepts a RegEx pattern, and then pipe that into Remove-Item. I think that will get you a faster, and better result than using Select-String. With a command like:

Get-ChildItem $Path | Where{$_.Name -Match "<RegEx Pattern>"} | Remove-Item

Name属性将仅与文件或文件夹的名称以及文件的扩展名匹配.它不会与沿途的其他事物相匹配.这将沿管道传递FileInfo对象,Remove-Item将其作为管道输入,并删除有问题的文件.

The Name attribute will only match the name of the file or folder, along with a file's extension. It will not match against other things along the path. This will pass a FileInfo object down the pipe, which Remove-Item takes as piped input and will remove the files in question.

如果要包括路径的子文件夹,可以将-Recurse开关添加到Get-ChildItem命令中,如下所示:

If you want to include sub folders of your path you would add the -Recurse switch to your Get-ChildItem command, and it would look like this:

Get-ChildItem $Path -Recurse | Where{$_.Name -Match "<RegEx Pattern>"} | Remove-Item

如果只想删除文件,则可以在Where语句中通过查看FileInfo对象的PSIsContainer属性并通过在该对象前加上感叹号将其反转来指定它,例如:

If you only want to delete files you can specify that in the Where statement by looking at the FileInfo object's PSIsContainer property and inverting it by prefixing the object with an exclamation point like such:

Get-ChildItem $Path -Recurse | Where{$_.Name -Match "<RegEx Pattern>" -and !$_.PSIsContainer} | Remove-Item

这篇关于如何使用PowerShell删除与正则表达式匹配的文件夹中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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