(adapted from this forum answer by foxidrive) Recurse through all the folders below C:\demo and if any have the name "version 1" rename to "version OffįOR /D /R %%a in (C:\demo) DO if "%~Na" equ "version 1" ren "%%a" "version 2" List every subfolder, below the folder C:\Work\ that has a name starting with OffįOR /D /r %%G in ("User*") DO Echo We found %%~nxG Parameter expansion will treat a Full Stop as a file extension, so for a directory name like " Sample 2.6.4" the output of %%~nG will be truncated to " Sample 2.6" to return the whole folder name use %%G or %%~nxGįOR does not, by itself, set or clear the Errorlevel.
Or the same thing in a batch file, with the %'s doubled:įor /f "tokens=*" %%G in ('dir /b /s /a:d "C:\Work\reports*"') do echo Found %%G Period/Full StopĪlthough Win32 will not recognise any file or directory name that begins or ends with a '.' (period / full stop) it is possible to include a Full Stop in the middle of a directory name and this can cause issues with FOR /D. To loop through each folder programatically, we can wrap that in a FOR /F command:Ĭ:\> for /f "tokens=*" %G in ('dir /b /s /a:d "C:\Work\reports*"') do echo Found %G AlternativesĪn alternative command to list folders and sub folders matching a wildcard is DIR: The option /d /r is undocumented, but can be a useful combination, while it will recurse through all subfolders the wildcard will only match against Folder/Directory names (not filenames). If specifying a full path to any of the folders, the path separators must use a backslash, not a forward slash. If any path in the the folder_set includes spaces, then surround the path with double quotes. if you are looping through multiple folders to find the exact folder January you could instead specify Janu?ry In many cases you can work around this by adding a single character wildcard e.g.
Unlike other variants of the FOR command you must include a wildcard (either * or ?) in the ' folder_set' to get consistent results returned. In all cases for /d will start searching from the current directory. r : Recurse into subfolders (see notes below) In a batch file use %%G (on the command line %G) In ( brackets), several commands, one per line. This can be a single command, or if you enclose it SyntaxįOR /D %% parameter IN ( folder_set) DO commandįolder_set : A set of one or more folders enclosed in parentheses (folder1,folder2).Ĭommand : The command to carry out, including any parameters.
Conditionally perform a command on several Directories/Folders.