且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用PowerShell删除与正则表达式匹配的文件夹中的文件?

更新时间:2023-02-26 12:09:20

您可以通过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