简体   繁体   English

使用Powershell和.txt文件删除多个文件

[英]Delete multiple files using powershell and a .txt file

I have a .txt with the names of over 1000 files I want to delete. 我有一个.txt,其中包含我要删除的1000多个文件的名称。 My .txt file does not have file paths. 我的.txt文件没有文件路径。 The files I want to delete are spread throughout multiple folders but they are all in the same drive. 我要删除的文件分布在多个文件夹中,但是它们都在同一驱动器中。 Is there any way to use powershell or command prompt to search for all files within my drive with the same name as what is listed in my .txt file and delete them? 有什么方法可以使用Powershell或命令提示符在驱动器中搜索与.txt文件中列出的名称相同的所有文件并将其删除吗?

Assuming you're PowerShell prompt is currently set at the root location from which you want to start your search and the file is in the same directory: 假设您当前是PowerShell提示符,并且该提示符位于您要开始搜索的根位置,并且文件位于同一目录中:

gc .\MyListOfFilesIWantToDelete.txt | %{gci $_ -Recurse | Remove-Item -WhatIf}

Note, you'll have to remove the -whatif 请注意,您必须删除-whatif

Or, let's say your file is somewhere else where you have PowerShell opened (eg: ~/Documents), and you want to scan your D: drive. 或者,假设您的文件位于打开PowerShell的其他位置(例如:〜/ Documents),并且您想扫描D:驱动器。 This should work: 这应该工作:

gc .\MyListOfFilesIWantToDelete.txt | %{gci D:\ -Filter $_ -Recurse -ErrorAction SilentlyContinue | Remove-Item -WhatIf}

Note I put SilentlyContinue. 注意我把SilentlyContinue。 This is because you'll see a lot of red if you don't have access to folders in your search path. 这是因为如果您无法访问搜索路径中的文件夹,则会看到很多红色。

Alternatively, you can load up a variable with your list of files.. 或者,您可以在文件列表中加载变量。

$thesefiles = gc .\mylistoffilesiwanttodelete.txt

.. and use the Remove-Item cmdlet directly.. ..并直接使用Remove-Item cmdlet。

Remove-Item -Path D:\Folder -Include $thesefiles -Recurse -WhatIf

or in one swoop without loading a variable: 或一口气不加载变量:

Remove-Item -Path D:\Folder -Include $(gc .\mylistoffilesiwanttodelete.txt) -Recurse -WhatIf

Again, I'm using -WhatIf for testing. 同样,我使用-WhatIf进行测试。 Also, I've noticed different behaviors in the past with get-childitem on different versions of PowerShell. 另外,我注意到过去在不同版本的PowerShell上使用get-childitem会出现不同的行为。 I tested these with 5.1 我用5.1测试了这些

Change directory from following powershell command 从以下Powershell命令更改目录

Following command will allow you to delete .txt files in specific directory 以下命令将允许您删除特定目录中的.txt文件

Get-ChildItem C:\*.txt -file -r | remove-item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM