Scott Mayo
Scott Mayo

Reputation: 11

How to delete specific hidden sub folders recursively with batch

A bad program left several ".data" hidden folders in every sub directory.

I have tried this so far, and it doesn't work...

RD /ah /s /q "D:\This Folder\.data"

I have many folders and sub-folders, each one has a ".data" hidden folder there that I would like to remove. If it helps, I would like to delete all the hidden folders because they are all ".data".

Upvotes: 1

Views: 745

Answers (3)

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion
    for /f "delims= eol=" %%a in ('
        dir /adh /s /b 2^>nul 
    ') do if /i "%%~nxa"==".data" echo rd /s /q "%%~fa"

This executes a dir command to retrieve a recursive (/s) list of hidden directories (/ahd) in bare format (/b). This list is processed by a for /f command that will check for each match if it is a .data folder. If it matches the condition, the folder and its contents are removed.

note the rd commands are only echoed to console. If the output is correct, remove the echo command.

Upvotes: 4

Andy Morris
Andy Morris

Reputation: 3503

Read what you get when you type for /? then:

Use the /d

FOR /D %variable IN (set) DO command [command-parameters]

    If set contains wildcards, then specifies to match against directory
    names instead of file names.

and the /r switches together

FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]

Walks the directory tree rooted at [drive:]path, executing the FOR
statement in each directory of the tree.  If no directory
specification is specified after /R then the current directory is
assumed.  If set is just a single period (.) character then it
will just enumerate the directory tree.

To scan folders recursivly

for /d /r . %%a in (data*) do rd /s /q "%%a"

Upvotes: 0

MichaelS
MichaelS

Reputation: 6032

@ECHO OFF
for /f "tokens=*" %%F in ('dir /s /b /o:n /adh') do (
    if "%%~nxF"==".data" rd /s /q "%%F"
)

dir /s /b /o:n /adh gives you all folders and subfolders skipping files. for /f iterates over all these folders. %%~nxF extracts the last folder name from the whole path so we can check whether it is .data. If this is the case rd /s /q %%F deletes the folder.

Upvotes: 1

Related Questions