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

或者,為了使其盡可能短,您可以簡單地執行以下操作,因為 EvenRemove-Item有一個過濾器:

del $ParentPath\*(Beta)* -Force

Get-ChildItem由於 PowerShell 中的所有內容都是對象,因此您可以簡單地過濾(或任何其他 cmdlet)使用Where-Object或其別名返回的對象?

在這種情況下,由於Get-ChildItemRemove-Item有一個-filter參數,你甚至可以得到你想要的對象,而不需要Where-Object

相關內容