Search code examples
batch-filecmdcycleprefixsubdirectory

Get subdirectories with specific prefix


I'm creating simple batch script for deleting all user configs of specific application and I'm still failing on the last step where I'm trying to get all subfolders with specific prefix...

This is what I have right now:

@echo off
chcp 1250

SET appUserConfigDirectory=\AppData\Local\CompanyName
SET appConfigFolderPrefix=AppName.exe_Url

:: get parent folder of user folders
for %%d in (%USERPROFILE%) do SET userprofilesFolder=%%~dpd

SETLOCAL ENABLEDELAYEDEXPANSION
:: going through all user folders
for /F "delims=" %%d in ('dir %userprofilesFolder% /A:D-R-H-S /b') do (
    :: set full name of CompanyName folder in user AppData
    SET appConfigParentFolder=%userprofilesFolder%%%d%appUserConfigDirectory%
    IF EXIST !appConfigParentFolder! (
        :: There is a problem with dir command, it's says File not found even if subfolder with this prefix exists and print all subFolder no metter it's name...
        for /F "delims=" %%i in ('dir !appConfigParentFolder! /A:D /b %appConfigFolderPrefix%*') do (
        echo %%i)))

Solution

  • I find the way how to do it. The right dir command with prefix should be:

    dir !appConfigParentFolder!\%appConfigFolderPrefix%* /A:D /b
    

    So the full version of this sample is:

    @echo off
    chcp 1250
    
    SET appUserConfigDirectory=\AppData\Local\CompanyName
    SET appConfigFolderPrefix=AppName.exe_Url
    
    for %%d in (%USERPROFILE%) do SET userprofilesFolder=%%~dpd
    
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    for /F "delims=" %%d in ('dir %userprofilesFolder% /A:D-R-H-S /b') do (
        SET appConfigParentFolder=%userprofilesFolder%%%d%appUserConfigDirectory%
        IF EXIST !appConfigParentFolder! (
            for /F "delims=" %%i in ('dir !appConfigParentFolder!\%appConfigFolderPrefix%* /A:D /b') do echo %%i
        )
    )