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)」が含まれるすべてのファイルを一括削除しようとしています。上に貼り付けた出力は、私が書いたコードと出力を示しています。ご覧のとおり、名前にその文字列が含まれていても、文字列は「一致しませんでした」。

私は初心者で、ドキュメントを理解しようとしていますが、読んだところすべてにおいて -contains ではなく -match を使うべきだと書かれています。

どのような助けでも大歓迎です。

答え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

受け入れられた答えは機能し、コードを修正しますが、シェルでも直接使用できる非常に使いやすいソリューションを紹介したいと思います。

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

または、おそらく可能な限り最短にするには、even にRemove-Itemフィルターがあるため、次のように実行します。

del $ParentPath\*(Beta)* -Force

PowerShell のすべてがオブジェクトであるため、Get-ChildItem(またはその他のコマンドレット)Where-Objectがまたはそのエイリアスを使用して返すオブジェクトを簡単にフィルターできます?

この場合、とにはGet-ChildItemパラメータRemove-Itemがあるため-filter、必要なオブジェクトを必要とせずに取得することもできます。Where-Object

関連情報