Powershell - 批量删除包含某些字符串的文件?

Powershell - 批量删除包含某些字符串的文件?
PS C:\RetroArch-Win64\_ROMS\nointro.n64> foreach ($file in (get-childitem $ParentFolder)){
>> write-verbose "($file.name)" -Verbose
>> if ((get-content $file.name) -match '(Beta)'){
>> write-verbose "found the string, deleting" -Verbose
>> remove-item $file.name -force -WhatIf
>> }else{ write-verbose "Didnt match" -Verbose
>> }
>>
>> }
VERBOSE: (007 - The World Is Not Enough (Europe) (En,Fr,De).7z.name)
VERBOSE: Didnt match
VERBOSE: (007 - The World Is Not Enough (USA) (v2) (Beta).7z.name)
VERBOSE: Didnt match
VERBOSE: (007 - The World Is Not Enough (USA) (v21) (Beta).7z.name)
VERBOSE: Didnt match
VERBOSE: (007 - The World Is Not Enough (USA).7z.name)
PS C:\RetroArch-Win64\_ROMS\nointro.n64>

我正在尝试批量删除名称包含字符串“(Beta)”的所有文件。上面粘贴的输出显示了我编写的代码和输出。如您所见,即使名称包含该字符串,它也会“不匹配”该字符串。

我是个新手,正在尝试理解文档,但我读到的所有地方都应该使用 -match 而不是 -contains。

非常感谢您的帮助。

答案1

如果你尝试匹配包含字符串的文件名(Beta),则不应使用Get-Content。使用时Get-Content,你将打开文件并在其内容/值中查找(Beta)失败的单词。

你应该只测试文件名。你的代码应该是:

ForEach ($file in (Get-ChildItem $ParentFolder)){
    Write-Verbose "($file.name)" -Verbose
    if ($file.Name -Match '(Beta)'){
       Write-Verbose "found the string, deleting" -Verbose
       Remove-Item $file.Name -WhatIf
    }else{ Write-Verbose "Didnt match" -Verbose}
 }

答案2

虽然接受的答案有效并纠正了你的代码,但我只是想向你展示一个非常容易使用的解决方案,也可以直接在 shell 中使用

Get-ChildItem $ParentFolder | Where-Object { $_.Name -like '*(Beta)*' } | Remove-Item -force

或者简而言之:

gci $ParentFolder | ? Name -like '*(Beta)*' | del -Force

实际上,我们可以让它更短,因为Get-ChildItem有一个-Filter参数

gci $ParentFolder -Filter '*(Beta)*' | del -force

或者,为了使它尽可能最短,您可以简单地执行以下操作,因为甚至Remove-Item有一个过滤器:

del $ParentPath\*(Beta)* -Force

由于 PowerShell 中的所有内容都是对象,因此您可以简单地过滤使用或其别名返回的对象Get-ChildItem(或任何其他 cmdlet)。Where-Object?

在这种情况下,由于Get-ChildItemRemove-Item有一个-filter参数,你甚至可以得到你想要的对象,而不需要Where-Object

相关内容