Francisco Lopes
Francisco Lopes

Reputation: 43

How to find folders that containt a certain string using CMD?

I need to find the path of every folder that contains the words "test" or "Test" or "TEST" in a specific location. The file tree is huge.

This is to remove every folder that contains "test". I've tried using the findstr function.

findstr /i "test"

I expect to get every folder path that contains "test"

Upvotes: 0

Views: 4022

Answers (1)

lit
lit

Reputation: 16236

The list of directories can be generated and iterated over using a FOR loop. When you are satisfied that the correct directories will be deleted, remove the echo from the line containing rmdir.

@echo off
pushd \
for /f "delims=" %%a in ('dir /s /b /a:d "*test*"') do (
    echo if exist "%%~a" (rmdir /s /q "%%~a")
)
popd

If you wanted to push ahead into Powershell, which Microsoft says is the future, something like this might work. When you are satisfied that the correct directories will be removed, remove the -WhatIf from the Remove-Item cmdlet.

=== Remove-TestDirectories.ps1

$previousdir = ":" # set to impossible filesystem name

Get-ChildItem -Directory -Recurse -Path "C:\" -Filter "*test*" -Force -ErrorAction SilentlyContinue |
    Sort-Object -Property FullName |
    ForEach-Object {
        #"{0} and {1} and {2}" -f @($previousdir, $_.FullName, $_.FullName.StartsWith($previousdir))
        if (-not $_.FullName.StartsWith($previousdir)) {
            $previousdir = $_.FullName
            if (Test-Path -Path $_.FullName) { Remove-Item -Path $_.FullName -Recurse -WhatIf}
        }
    }

This can be run from a cmd.exe shell.

powershell -NoLogo -NoProfile -File Remove-TestDirectories.ps1

Upvotes: 1

Related Questions