Link to home
Start Free TrialLog in
Avatar of Luis Diaz
Luis DiazFlag for Colombia

asked on

Windows Batch & Powershell: remove files based on multiple strings

Hello experts,

I am looking for a script that cover the following requirement:
Remove all files located in a folder which start with specific string.
The idea is to declare specific string multiple times in a variable.
Example
StringToRemove = “KO”; ‘OLD”; "ERR"
All the files which contain those string reported in StringToRemove should be removed.
Drill down mode required. In order to also remove all files located in subfolders.

Windows Batch & PowerShell & Vb Script are more than welcome.

If you have question, please contact me.

Thank you for your help.
EXPERT CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oBdA
oBdA

In PowerShell like this, for example (in test mode, remove the -WhatIf to run it for real):
$stringToRemove = 'KO', 'OLD', 'ERR'

$includePattern  = $stringToRemove | ForEach-Object {"$($_)*"}
Get-Childitem -Path C:\Target -File -Recurse -Include $includePattern -WhatIf

Open in new window

Avatar of Luis Diaz

ASKER

Thank you very much. I will test it and keep you informed.
Bill:
I tested your proposal but I got the following message displayed:
KO*.*

Open in new window

With a file that is named as following:
New Text Document - Copy_KO.txt
and file is not removed.
Thank you for your help.
@oBdA:

I tested your proposal but I got the following message:

Get-ChildItem : A parameter cannot be found that matches parameter name 'WhatIf'.

Open in new window


And I have the following file at folder:
New Text Document - Copy_KO.txt

I tested as following:

$CurrentDir = Split-Path $script:MyInvocation.MyCommand.Path
$Root = $CurrentDir + '\RefFolder'
$stringToRemove = 'KO', 'OLD', 'ERR'

$includePattern  = $stringToRemove | ForEach-Object {"$($_)*"}
Get-Childitem -Path $Root -File -Recurse -Include $includePattern -WhatIf

Open in new window


Thank you for your help.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for your feedback.
I will test them and keep you informed.
@Bill: Thank you very much for your help. It works. Sorry for this change.
@OBdA: I was wondering how should I change {"$($_)*"} for contains.
The idea is to remove all files which contains $stringToRemove.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tested and it works!

Thank you again for your great support!