Powershell - batch delete files CONTAINING some string?

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>

I am trying to batch delete all files whose name CONTAINS the string '(Beta)'. The output pasted above shows the code I wrote and the output. As you can see it 'Didnt match' the string even though the names contain that string.

I am a noobie and trying to understand the docs, but everywhere I read I should use -match not -contains.

Any help greatly appreciated.


Solution 1:

If you are trying to match filenames which contains the string (Beta), then you should not use Get-Content. With Get-Content, you are opening the files and looking in their contents/values for the word (Beta) which is failing.

You should only test the filename. Your code should be:

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}
 }

Solution 2:

While the accepted answer works and corrects your code, i simply want to show you a solution that would be very easy to use, also in the shell directly

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

or in short:

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

actually, we can make it even shorter, since Get-ChildItem has a -Filter parameter

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

or, to make it probably the shortest thing possible, you can simply do the following, since even Remove-Item has a filter:

del $ParentPath\*(Beta)* -Force

since everything in PowerShell is an object, you can simply filter the objects that Get-ChildItem (or any other cmdlet) returns with Where-Object or its alias ?.

In this case, since Get-ChildItem and Remove-Item have a -filter parameter, you can even get your desired objects it without the need of Where-Object