Using wildcards with the rd command inside for

I want to delete all folders starting with "machine.contoso.com" (including all subfolders and files). I tried this command:

I get an error, though :(

cd c:\Program Files\Software\Temp
for /f %i in ('dir /a:d /s /b machine.contoso.com*') do rd /s /q %i

error:

rd /s /q C:\Program
The system cannot find the file specified.

Folder Structure:

machine.contoso.com_1611940173
machine.contoso.com_1611323243
machine.contoso.com_1611645665
machine.contoso.com_1611940176
machine.contoso.com_1611940177
HOSTNAME.contoso.com_com_1811940177
HOSTNAME.contoso.com_com_1813435435
HOSTNAME.contoso.com_com_1811940456
HOSTNAME.contoso.com_com_1811345463
HOSTNAME.contoso.com_com_1813523454

thanks,


Solution 1:

You can replace your For /F to For /R /D

cd /d  "C:\Program Files\Software\Temp\" && for /r /d %i in (*contoso*)do rmdir /q /s "%~dpnxi"

You can use the For /D /R loop, which will go through all the folders, and in each folder inside the loop, use the RMDir command to delete the current folder in the loop and all files/subfolders.

Obs. 1 You can use machine.contoso.com*, m*.contoso.com*, m*.c*.com.*, m*.c*.c*.*, etc... in your loop for loop ..(strings)do...

Obs. 2 But keep in mind that you will probably need to run as an administrator to delete items in %ProgramFiles%.


  • Some further reading:

    • For Loop

    • For /D Loop

    • For /R Loop

    • Conditional Execution || && ...