How to delete files/subfolders in a specific directory at the command prompt in Windows - windows

Say, there is a variable called %pathtofolder%, as it makes it clear it is a full path of a folder.
I want to delete every single file and subfolder in this directory, but not the directory itself.
But, there might be an error like 'this file/folder is already in use'... when that happens, it should just continue and skip that file/folder.
Is there some command for this?

rmdir is my all time favorite command for the job. It works for deleting huge files and folders with subfolders. A backup is not created, so make sure that you have copied your files safely before running this command.
RMDIR "FOLDERNAME" /S /Q
This silently removes the folder and all files and subfolders.

You can use this shell script to clean up the folder and files within C:\Temp source:
del /q "C:\Temp\*"
FOR /D %%p IN ("C:\Temp\*.*") DO rmdir "%%p" /s /q
Create a batch file (say, delete.bat) containing the above command. Go to the location where the delete.bat file is located and then run the command: delete.bat

The simplest solution I can think of is removing the whole directory with
RD /S /Q folderPath
Then creating this directory again:
MD folderPath

This will remove the folders and files and leave the folder behind.
pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)

#ECHO OFF
SET THEDIR=path-to-folder
Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A
Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
#ECHO Folder deleted.
EXIT
...deletes all files and folders underneath the given directory, but not the directory itself.

CD [Your_Folder]
RMDIR /S /Q .
You'll get an error message, tells you that the RMDIR command can't access the current folder, thus it can't delete it.
Update:
From this useful comment (thanks to Moritz Both), you may add && between, so RMDIR won't run if the CD command fails (e.g. mistyped directory name):
CD [Your_Folder] && RMDIR /S /Q .
From Windows Command-Line Reference:
/S: Deletes a directory tree (the specified directory and all its
subdirectories, including all files).
/Q: Specifies quiet mode. Does not prompt for confirmation when
deleting a directory tree. (Note that /q works only if /s is
specified.)

I use Powershell
Remove-Item c:\scripts\* -recurse
It will remove the contents of the folder, not the folder itself.

RD stands for REMOVE Directory.
/S : Delete all files and subfolders
in addition to the folder itself.
Use this to remove an entire folder tree.
/Q : Quiet - do not display YN confirmation
Example :
RD /S /Q C:/folder_path/here

Use Notepad to create a text document and copy/paste this:
rmdir /s/q "%temp%"
mkdir "%temp%"
Select Save As and file name:
delete_temp.bat
Save as type: All files and click the Save button.
It works on any kind of account (administrator or a standard user). Just run it!
I use a temporary variable in this example, but you can use any other! PS: For Windows OS only!

None of the answers as posted on 2018-06-01, with the exception of the single command line posted by foxidrive, really deletes all files and all folders/directories in %PathToFolder%. That's the reason for posting one more answer with a very simple single command line to delete all files and subfolders of a folder as well as a batch file with a more complex solution explaining why all other answers as posted on 2018-06-01 using DEL and FOR with RD failed to clean up a folder completely.
The simple single command line solution which of course can be also used in a batch file:
pushd "%PathToFolder%" 2>nul && ( rd /Q /S "%PathToFolder%" 2>nul & popd )
This command line contains three commands executed one after the other.
The first command PUSHD pushes current directory path on stack and next makes %PathToFolder% the current directory for running command process.
This works also for UNC paths by default because of command extensions are enabled by default and in this case PUSHD creates a temporary drive letter that points to that specified network resource and then changes the current drive and directory, using the newly defined drive letter.
PUSHD outputs following error message to handle STDERR if the specified directory does not exist at all:
The system cannot find the path specified.
This error message is suppressed by redirecting it with 2>nul to device NUL.
The next command RD is executed only if changing current directory for current command process to specified directory was successful, i.e. the specified directory exists at all.
The command RD with the options /Q and /S removes a directory quietly with all subdirectories even if the specified directory contains files or folders with hidden attribute or with read-only attribute set. The system attribute does never prevent deletion of a file or folder.
Not deleted are:
Folders used as the current directory for any running process. The entire folder tree to such a folder cannot be deleted if a folder is used as the current directory for any running process.
Files currently opened by any running process with file access permissions set on file open to prevent deletion of the file while opened by the running application/process. Such an opened file prevents also the deletion of entire folder tree to the opened file.
Files/folders on which the current user has not the required (NTFS) permissions to delete the file/folder which prevents also the deletion of the folder tree to this file/folder.
The first reason for not deleting a folder is used by this command line to delete all files and subfolders of the specified folder, but not the folder itself. The folder is made temporarily the current directory for running command process which prevents the deletion of the folder itself. Of course this results in output of an error message by command RD:
The process cannot access the file because it is being used by another process.
File is the wrong term here as in reality the folder is being used by another process, the current command process which executed command RD. Well, in reality a folder is for the file system a special file with file attribute directory which explains this error message. But I don't want to go too deep into file system management.
This error message, like all other error messages, which could occur because of the three reasons written above, is suppressed by redirecting it with 2>nul from handle STDERR to device NUL.
The third command, POPD, is executed independently of the exit value of command RD.
POPD pops the directory path pushed by PUSHD from the stack and changes the current directory for running the command process to this directory, i.e. restores the initial current directory. POPD deletes the temporary drive letter created by PUSHD in case of a UNC folder path.
Note: POPD can silently fail to restore the initial current directory in case of the initial current directory was a subdirectory of the directory to clean which does not exist anymore. In this special case %PathToFolder% remains the current directory. So it is advisable to run the command line above not from a subdirectory of %PathToFolder%.
One more interesting fact:
I tried the command line also using a UNC path by sharing local directory C:\Temp with share name Temp and using UNC path \\%COMPUTERNAME%\Temp\CleanTest assigned to environment variable PathToFolder on Windows 7. If the current directory on running the command line is a subdirectory of a shared local folder accessed using UNC path, i.e. C:\Temp\CleanTest\Subfolder1, Subfolder1 is deleted by RD, and next POPD fails silently in making C:\Temp\CleanTest\Subfolder1 again the current directory resulting in Z:\CleanTest remaining as the current directory for the running command process. So in this very, very special case the temporary drive letter remains until the current directory is changed for example with cd /D %SystemRoot% to a local directory really existing. Unfortunately POPD does not exit with a value greater 0 if it fails to restore the initial current directory making it impossible to detect this very special error condition using just the exit code of POPD. However, it can be supposed that nobody ever runs into this very special error case as UNC paths are usually not used for accessing local files and folders.
For understanding the used commands even better, open a command prompt window, execute there the following commands, and read the help displayed for each command very carefully.
pushd /?
popd /?
rd /?
Single line with multiple commands using Windows batch file explains the operators && and & used here.
Next let us look on the batch file solution using the command DEL to delete files in %PathToFolder% and FOR and RD to delete the subfolders in %PathToFolder%.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Clean the folder for temporary files if environment variable
rem PathToFolder is not defined already outside this batch file.
if not defined PathToFolder set "PathToFolder=%TEMP%"
rem Remove all double quotes from folder path.
set "PathToFolder=%PathToFolder:"=%"
rem Did the folder path consist only of double quotes?
if not defined PathToFolder goto EndCleanFolder
rem Remove a backslash at end of folder path.
if "%PathToFolder:~-1%" == "\" set "PathToFolder=%PathToFolder:~0,-1%"
rem Did the folder path consist only of a backslash (with one or more double quotes)?
if not defined PathToFolder goto EndCleanFolder
rem Delete all files in specified folder including files with hidden
rem or read-only attribute set, except the files currently opened by
rem a running process which prevents deletion of the file while being
rem opened by the application, or on which the current user has not
rem the required permissions to delete the file.
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
rem Delete all subfolders in specified folder including those with hidden
rem attribute set recursive with all files and subfolders, except folders
rem being the current directory of any running process which prevents the
rem deletion of the folder and all folders above, folders containing a file
rem opened by the application which prevents deletion of the file and the
rem entire folder structure to this file, or on which the current user has
rem not the required permissions to delete a folder or file in folder tree
rem to delete.
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
:EndCleanFolder
endlocal
The batch file first makes sure that environment variable PathToFolder is really defined with a folder path without double quotes and without a backslash at the end. The backslash at the end would not be a problem, but double quotes in a folder path could be problematic because of the value of PathToFolder is concatenated with other strings during batch file execution.
Important are the two lines:
del /A /F /Q "%PathToFolder%\*" >nul 2>nul
for /F "eol=| delims=" %%I in ('dir "%PathToFolder%\*" /AD /B 2^>nul') do rd /Q /S "%PathToFolder%\%%I" 2>nul
The command DEL is used to delete all files in the specified directory.
The option /A is necessary to process really all files including files with the hidden attribute which DEL would ignore without using option /A.
The option /F is necessary to force deletion of files with the read-only attribute set.
The option /Q is necessary to run a quiet deletion of multiple files without prompting the user if multiple files should be really deleted.
>nul is necessary to redirect the output of the file names written to handle STDOUT to device NUL of which can't be deleted because of a file is currently opened or user has no permission to delete the file.
2>nul is necessary to redirect the error message output for each file which can't be deleted from handle STDERR to device NUL.
The commands FOR and RD are used to remove all subdirectories in specified directory. But for /D is not used because of FOR is ignoring in this case subdirectories with the hidden attribute set. For that reason for /F is used to run the following command line in a separate command process started in the background with %ComSpec% /c:
dir "%PathToFolder%\*" /AD /B 2>nul
DIR outputs in bare format because of /B the directory entries with attribute D, i.e. the names of all subdirectories in specified directory independent on other attributes like the hidden attribute without a path. 2>nul is used to redirect the error message output by DIR on no directory found from handle STDERR to device NUL.
The redirection operator > must be escaped with the caret character, ^, on the FOR command line to be interpreted as a literal character when the Windows command interpreter processes this command line before executing the command FOR which executes the embedded dir command line in a separate command process started in the background.
FOR processes the captured output written to handle STDOUT of a started command process which are the names of the subdirectories without path and never enclosed in double quotes.
FOR with option /F ignores empty lines which don't occur here as DIR with option /B does not output empty lines.
FOR would also ignore lines starting with a semicolon which is the default end of line character. A directory name can start with a semicolon. For that reason eol=| is used to define the vertical bar character as the end-of-line character which no directory or file can have in its name.
FOR would split up the line into substrings using space and horizontal tab as delimiters and would assign only the first space/tab delimited string to specified loop variable I. This splitting behavior is not wanted here because of a directory name can contain one or more spaces. Therefore delims= is used to define an empty list of delimiters to disable the line splitting behavior and get assigned to the loop variable, I, always the complete directory name.
Command FOR runs the command RD for each directory name without a path which is the reason why on the RD command line the folder path must be specified once again which is concatenated with the subfolder name.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
rd /?
rem /?
set /?
setlocal /?

To delete file:
del PATH_TO_FILE
To delete folder with all files in it:
rmdir /s /q PATH_TO_FOLDER
To delete all files from specific folder (not deleting folder itself) is a little bit complicated. del /s *.* cannot delete folders, but removes files from all subfolder. So two commands are needed:
del /q PATH_TO_FOLDER\*.*
for /d %i in (PATH_TO_FOLDER\*.*) do #rmdir /s /q "%i"

You can do it by using the following command to delete all contents and the parent folder itself:
RMDIR [/S] [/Q] [drive:]path

#ECHO OFF
rem next line removes all files in temp folder
DEL /A /F /Q /S "%temp%\*.*"
rem next line cleans up the folder's content
FOR /D %%p IN ("%temp%\*.*") DO RD "%%p" /S /Q

I tried several of these approaches, but none worked properly.
I found this two-step approach on the site Windows Command Line:
forfiles /P %pathtofolder% /M * /C "cmd /c if #isdir==FALSE del #file"
forfiles /P %pathtofolder% /M * /C "cmd /c if #isdir==TRUE rmdir /S /Q #file"
It worked exactly as I needed and as specified by the OP.

I had following solution that worked for me:
for /R /D %A in (*node_modules*) do rmdir "%A" /S /Q
It removes all node modules folder from current directory and its sub-folders.
This is similar to solutions posted above, but i am still posting this here, just in case someone finds it useful

Use:
del %pathtofolder%\*.* /s /f /q
This deletes all files and subfolders in %pathtofolder%, including read-only files, and does not prompt for confirmation.

Related

How to include system variable in batch file inside FOR loop ? also escaping the ! and % sign inside variable?

lets say i have a list file contains folder names that i want to delete periodically based on a list,
currently using this batch file which don't work as i expected :
setlocal enabledelayedexpansion
for /F "tokens=2* delims==" %%x in ('findstr/brc:"foldertodelete" garbagefolderlist.txt') do (
set "foldertodelete=%%x"
set foldertodelete=!foldertodelete:"=!
set foldertodelete=!foldertodelete:%%=^!!"
echo !foldertodelete!
if exist !foldertodelete! (
echo deleting !foldertodelete!
rmdir /s /q !foldertodelete!>nul
)
)
endlocal
inside garbagefolderlist.txt :
foldertodelete="%programfiles%\blablabla"
fodlertodelete=%systemroot%\blablabla
foldertodelete="C:\Temp"
foldertodelete=D:\Temporary files\here
notes about the list file (garbagefolderlist.txt) :
1. folder names may contains double quotes or not, so i want to dynamically eliminate the double quotes inside batch file
2. folder names may be plain or using system variable or not like %systemroot%, etc
3. folder names may contains spaces
If all you want to do is delete the folders listed in that text file you only need one single line of code. You need to use the CALL command to get the double variable expansion that you require. You don't even need delayed expansion at all.
for /F "tokens=2* delims==" %%x in ('findstr /bc:"foldertodelete" garbagefolderlist.txt') do call rmdir /s /q "%%~x" 2>nul
Here is the execution of your script on my system. I created a folder in Program Files and I also have a Temp folder on the C: drive. The line in your file with %systemroot% will not be chosen because you have a typo on that line. So the script will only attempt to process three lines from your input example.
I have added the echo to the code and removed the error dump to nul so that you can see all the output.
#echo off
for /F "tokens=2* delims==" %%x in ('findstr /bc:"foldertodelete" garbagefolderlist.txt') do (
call echo %%~x
call rmdir /s /q "%%~x"
)
And here is the output of that code.
C:\BatchFiles\SO\71120676>so.bat
C:\Program Files\blablabla
Access is denied.
C:\Temp
D:\Temporary files\here
The system cannot find the path specified.
So lets break down that output.
You can see that the %programfiles% variable is expanded as it echo's the folder name correctly but the folder cannot be deleted because I am not running from an elevated cmd prompt as Administrator. So that folder cannot be deleted.
The temp folder displays correctly and is deleted.
The last directory does not exist on my system as I don't have a D: drive so the system reports that it cannot find the path. If standard error was still being redirected to the NUL device you would not see the error which is why I don't bother with checking if a folder exists before I delete it.

batch xcopy only files that are not present in destination

-TheGame/
- Game files/
-> file1.whatever
-> file2.whatever
-> file3.whatever
-> Launcher.exe
-TheGameModed/
- Game files/
-> file1.whatever (the moded file)
-> Launcher.exe (the moded launcher)
I made a mod on a game and i want to create an installer for people to play my game.
In order to preventing backup problems (if the player want to revert to vanilla) i will put the mod folder aside the game folder.
The mod folder contain only the "moded files" and in want to make a batch that will copy file from the game folder that are not already present in the destination (even if there are not the same)
Is this right :
xcopy "../TheGame" "../TheGameModed" /q /s /e
There is a documentation here but i didn't find what i'm looking for :
https://www.computerhope.com/xcopyhlp.htm
I found only this :
/U Copies only files that already exist in destination.
But i need the opposite (Copies only files that doesn't exist in destination)
P.S. : When the batch copy files, it ask me if i want to overwrite or not, and since i have only few filesit is not so hard to type n few times. But the mod will be deleted if someone type y (that would be bad) and maybe next mod will contain more files :[
Perhaps ROBOCOPY can't be used because the game updating batch file should work also on Windows XP. In this case the following batch file could be perhaps used working on Windows NT4 and all later Windows versions:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "%~dp0"
for /F "delims=" %%I in ('dir "TheGame\*" /A-D /B /S 2^>nul') do call :CopyFile "%%I"
popd
endlocal
exit
:CopyFile
set "SourcePath=%~dp1"
set "TargetPath=%SourcePath:\TheGame\=\TheGameModed\%"
if not exist "%TargetPath%%~nx1" %SystemRoot%\System32\xcopy.exe "%~1" "%TargetPath%" /C /I /Q >nul
goto :EOF
The batch file first creates a local environment.
Next it pushes path of current directory on stack and sets the directory of the batch file as current directory. It is expected by this batch file being stored in the directory containing the subdirectories TheGame and TheGameModed.
Then command DIR is executed to output
the names of just all files because of /A-D (attribute not directory)
with name of file only because of /B (bare format)
in specified directory TheGame and all subdirectories because of /S
and with full path also because of /S.
This DIR command line is executed in a separate command process started by FOR in background with cmd.exe /C which captures everything written by this command process respectively by DIR to handle STDOUT.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes DIR command line with using a separate command process started in background.
The FOR option delims= disables the standard behavior of splitting up each non empty line not starting with a semicolon into strings using space/tab as delimiter. In other words each file name with file extension and full path is assigned to loop variable I.
The name of each file with file extension and full path is passed to a subroutine called CopyFile.
The subroutine first assigns just path of source file found in TheGame directory tree to environment variable SourcePath. Next a string substitution is used to replace in this path TheGame by TheGameModed with including the directory separators on both side for more accuracy.
After having target path for current file in TheGame directory tree it is checked next if a file with that name in that path exists already in TheGameModed directory tree.
If the file does not exist, command XCOPY is used to copy this single file to TheGameModed with automatically creating the entire directory tree if that is necessary. This directory creation feature of XCOPY is the main reason for using XCOPY instead of COPY.
After processing all files in TheGame directory tree, the initial current directory is restored from stack as well as the initial environment before exiting current command process independent on calling hierarchy and how the command process was started initially.
The commands POPD and ENDLOCAL would not be really necessary with exit being the next line. I recommend usually to use exit /B or goto :EOF instead of EXIT, but goto :EOF fails if command extensions are not enabled and we can't be 100% sure that the command extensions are enabled on starting the batch file although by default command extensions are enabled on Windows.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
endlocal /?
exit /?
goto /?
if /?
popd /?
pushd /?
set /?
setlocal /?
xcopy /?

How do I make a batch file delete it's own directory?

Okay, I apologize that I am very new at this, but I am trying to make my batch file delete it's own directory after it has been launched. This is how my folders are arranged:
Folder1
delete.bat
My goal is to make "delete.bat" delete "Folder1" after "delete.bat" has been launched. So here's my code:
rd /s /q %~dp0..\Folder1
This seems like it would work but it only deletes the contents of "Folder1" rather than the whole directory itself. What am I doing wrong?
Some thoughts...
%~dp0 gets the drive and path of the batch file, so you don't need to include ..\Folder1.
What you have should work. If it's not removing the folder itself, it means that it's locked, probably because cmd's current folder is Folder1. (That's a likely guess, but it's not the only reason it might be locked.) If it is cmd, you'll have to call the batch file from another folder, outside of Folder1.
While what you have will work, it will result in a funny error when resuming the non-existent batch file: The system cannot find the path specified. You can avoid that in the solution below.
One good solution: start /b "" cmd /c rd /s /q "%~dp0"
This creates a new process to remove the folder (and everything in it, including the batch file itself). Be careful. =)
From the corresponding MSDN link for rd:
You cannot use rmdir to delete the current directory. You must first change to a different directory (not a subdirectory of the current directory) and then use rmdir with a path.
I guess this is what's going wrong in your case since the batch file is located within the directory that you're trying to delete.
My implementation is effectively the same as Soja's, plus the info from dbenham's comment. I have added a 2-sec delay, to ensure there are no timing issues, even though I believe the error when the .bat file is deleting itself is harmless.
#echo off
:: Do the work
...your command here...
:: In order to delete the current dir we are running from (and all subdirs), none of them can be the
:: current working directory of any running process. Therefore, we are setting our own CWD to something
:: else, so it will be inherited by the below cmd.exe.
cd /d %temp%
:: The countdown is there to allow this batch file to exit, so it can then be deleted safely.
set DelayedSelfDeleteCommand="timeout /t 2 >NUL && rmdir /s /q "%~dp0""
:: Start a separate process (without waiting for it), to execute the command
start "" /b cmd.exe /C %DelayedSelfDeleteCommand%
Well I think it cannot be done (at least as normal user)
start /b "" cmd /c rd /s "%~dp0"
deletes folder but only with right permissions I think
start /b "" cmd /c rmdir /s "C:/folder"
This has the same result
del /s /q "C:\Temp\folder\*"
rmdir /s /q "C:\Temp\folder"
del %0
only way as for batch files is to use vbs script or autohotkey (send !{Space} // send e // send p formula) or hack it, you can delete only file used and content of folder but not working directory due to specification of cmd. Any other language would have no problem with it cuz it in RAM memory.
I recommend this way to do it (as for normal users):
in your bat file add
copy C:\urpath\deleteafter.bat C:\Temp\deleteafter.bat
start "" autohotkey.exe "X:\patchto\deletebatchfile.ahk"
deletebatchfile.ahk
sleep 2000
Run, C:\Temp\deleteafter.bat, C:\Temp\
deleteafter.bat
rmdir /s /q "C:\Temp\batfileworkingpath"
sleep 3
del %0

copying all the elements of a folder into another folder using a loop in batch file

I want to copy all the files of a folder into some other folders using batch script. Say, I have two folders named folder1 and folder2. these two folders are located in C:\Users\xyz . I want to copy the elements of another folder (say, folder3 which is located in C:\Users\abc\def) into these two folders. I have made the following script but nothing is copied. My sample batch file is as follows:
FOR /L %%A IN (1,1,2) DO (
xcopy /s C:\Users\abc\def\folder3 C:\Users\xyz\folder%%A
)
is there anything wrong in the batch file?
xcopy /s C:\Users\abc\def\folder3\*.* C:\Users\xyz\folder%%A\
where *.* is an appropriate filemask and the final \ in the destination name tells cmd that the destination is a directory.
I suggest using this command line in the batch file:
for /L %%A in(1,1,2) do %SystemRoot%\System32\xcopy.exe "C:\Users\abc\def\folder3" "C:\Users\xyz\folder%%A\" /C /G /H /I /K /R /Q /S /Y >nul
I enclosed both directory paths in double quotes in case of real paths contain 1 or more spaces or other special characters which require double quotes. The last paragraph on last help page output by running in a command prompt window cmd /? outputs on which characters in a directory/file name double quotes are required around the complete directory/file name.
The target path ends with a backslash to make it clear for console application xcopy that the target is a directory and not a file. Together with the redundant /I the target directory is created if not existing already.
For details on the options used on xcopy open a command prompt window and run xcopy /?. This outputs the help for this console application in the command prompt window. On Windows running a command or console application with /? as parameter outputs in general the help for the command/application.
Note: The copying from one user profile directory to another user profile directory requires local administrator privileges. Each user profile directory is by default protected for exclusive usage of the owning user. Therefore I suggest to open a command prompt window and execute in this window:
for /L %A in(1,1,2) do %SystemRoot%\System32\xcopy.exe "C:\Users\abc\def\folder3" "C:\Users\xyz\folder%A\" /C /G /H /I /K /R /S /Y
You can see if that works with just %A as required on command line instead of %%A as required in batch files and without /Q (quiet copying) and without >nul (redirection of success messages to device NUL to suppress them). Or when it does not work, you can see why it does not work as the error message can be viewed on running a command or a batch file from within a command prompt window instead of double clicking on a batch file because the console window keeps open.

How to execute an application existing in each specific folder of a directory tree on a file in same folder?

I have some folders with different names. Each folder has a specific structure as listed below:
Folder1
Contents
x64
Folder1.aaxplugin
TransVST_Fixer.exe
Folder 2
Contents
x64
Folder 2.aaxplugin
TransVST_Fixer.exe
There are two files within each subfolder x64. One file has the same name as the folder two folder levels above. The other file is an .exe file whose name is the same in all folders.
Now I need to run file with file extension aaxplugin on each specific .exe file. It would be obviously very time consuming opening each and every single folder and drag & drop each file on .exe to run it on this file.
That's why I am trying to create a batch script to save some time.
I looked for solutions here on Stack Overflow. The only thing I have found so far was a user saying this: When I perform a drag & drop, the process 'fileprocessor.exe' is executed. When I try to launch this exe, though, CMD returns error ('not recognized or not batch file' stuff).
How can I do this?
UPDATE 12/22/2015
I used first a batch file with following line to copy the executable into x64 subfolder of Folder1.
for /d %%a in ("C:\Users\Davide\Desktop\test\Folder1\*") do ( copy "C:\Program Files\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%a\x64\" 2> nul )
After asking here, I tried the following script:
for /f "delims=" %%F in ('dir /b /s x64\*.aaxplugin') do "%%~dpFTransVST_Fixer.exe" "%%F"
Unfortunately, the output is as following
C:\Users\Davide\Desktop>for /F "delims=" %F in ('dir /b /s x64\*.aaxplugin') do "%~dpFTransVST_Fixer.exe" "%F"
The system cannot find the file specified.
Try the following batch code:
#echo off
setlocal EnableDelayedExpansion
for /R "%USERPROFILE%\Desktop\test" %%F in (*.aaxplugin) do (
set "FilePath=%%~dpF"
if not "!FilePath:\x64\=!" == "!FilePath!" "%ProgramFiles%\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%F"
)
endlocal
The command FOR with option/R searches recursive in all directories of directory %USERPROFILE%\Desktop\test being expanded on your machine to C:\Users\Davide\Desktop for files with file extension aaxplugin. The loop variable F contains on each loop run the name of the found file with full path without surrounding double quotes.
The drive and path of each found file is assigned to environment variable FilePath.
Next a case-sensitive string comparison is done between file path with all occurrences of string \x64\ case-insensitive removed with unmodified file path.
Referencing value of environment variable FilePath must be done here using delayed expansion because being defined and evaluated within a block defined with ( ... ). Otherwise command processor would expand %FilePath% already on parsing the entire block resulting in a syntax error on execution because string substitution is not possible as no environment variable FilePath defined above body block of FOR loop.
The strings are not equal if path of file contains a folder with name x64. This means on provided folder structure that the file is in folder x64 and not somewhere else and therefore the application is executed next from its original location to fix the found *.aaxplugin file.
The line with IF is for the folder structure example:
if not "C:\Users\Davide\Desktop\test\Folder1\Contents" == "C:\Users\Davide\Desktop\test\Folder1\Contents\x64\"
if not "C:\Users\Davide\Desktop\test\Folder 2\Contents" == "C:\Users\Davide\Desktop\test\Folder 2\Contents\x64\"
So for both *.aaxplugin files the condition is true because the compared strings are not identical
Also possible would be:
#echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%F in ('dir /A-D /B /S "%USERPROFILE%\test\*.aaxplugin" 2^>nul') do (
set "FilePath=%%~dpF"
if not "!FilePath:\x64\=!" == "!FilePath!" "%ProgramFiles%\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%F"
)
endlocal
But command DIR is not really necessary as it can be seen on first provided code.
But if the application TransVST_Fixer.exe for some unknown reason does its job right only with directory of file being also the current directory, the following batch code could be used instead of first code using the commands pushd and popd:
#echo off
setlocal EnableDelayedExpansion
for /R "%USERPROFILE%\test" %%F in (*.aaxplugin) do (
set "FilePath=%%~dpF"
echo !FilePath!
if /I "!FilePath:~-5!" == "\x64\" (
pushd "%%~dpF"
"%ProgramFiles%\Sugar Bytes\TransVST\TransVST_Fixer.exe" "%%~nxF"
popd
)
)
endlocal
There is one more difference in comparison to first code. Now the last 5 characters of path of file are compared case-insensitive with the string \x64\. Therefore the file must be really inside a folder with name x64 or X64. A folder with name x64 or X64 anywhere else in path of file does not result anymore in a true state for the condition as in first two batch codes.
But if for some unknown reason it is really necessary to run the application in same folder as the found *.aaxplugin and the directory of the file must be the current directory, the following batch code could be used:
#echo off
setlocal EnableDelayedExpansion
for /R "%USERPROFILE%\test" %%# in (*.aaxplugin) do (
set "FilePath=%%~dp#"
if /I "!FilePath:~-5!" == "\x64\" (
pushd "%%~dp#"
"%%~dp#TransVST_Fixer.exe" "%%~nx#"
popd
)
)
endlocal
The path of the file referenced with %%~dpF always ends with a backslash which is the reason why there is no backslash left of TransVST_Fixer.exe (although command processor could handle also file with with two backslashes in path).
In batch code above character # is used as loop variable because %%~dp#TransVST_Fixer.exe is easier to read in comparison to %%~dpFTransVST_Fixer.exe. It is more clear for a human with using # as loop variable where the reference to loop variable ends and where name of application begins. For the command processor it would not make a difference if loop variable is # or upper case F.
A lower case f would work here also as loop variable, but is in general problematic as explained on Modify variable within loop of batch script.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
echo /?
endlocal /?
for /?
if /?
popd /?
pushd /?
set /?
setlocal /?
Your question isn't quite clear, but it seems, something like this should work:
for /f "delims=" %%f in ('dir /b /s X64\*.ext') do "%%~dpfMyExe.exe" "%%f"
Maybe you have to change directory to each folder (depends on your .exe):
for /f "delims=" %%d in ('dir /B /ad') do (
pushd "%%d"
for /f "delims=" %%f in ('dir /b "contents\x64\*.ext"') do (
cd Contents\x64
MyExe.exe "%%f"
)
popd
)
Assuming:
The Directory structure is fixed and the files are indeed in a subfolder contents\X64\.
MyExe.exe is the same (name) in every folder.
There is only one file *.ext in every folder.
I'll give you the script I created for doing so, hope it works for you
for /d %%d IN (./*) do (cd "%%d/Contents/x64" & "../../../TransVST_Fixer.exe" "%%d" & cd "/Program Files (x86)\Common Files\Avid\Audio\Plug-Ins")
Please note that I placed the fixer inside the root folder so I just have to copy it once. You have to place it inside your root folder and execute it. What it does:
iterate over each folder
for each one it enters /Contents/x64, executes the fixer (wich is 3 levels above) and after that returns to the original folder.
If you have your plugins in a different folder, you just have to change this part replacing the path for the one you have your plugins in.
cd "/Program Files (x86)\Common Files\Avid\Audio\Plug-Ins"
REMEMBER to place the script on that folder. For this example I place my script on the folder "/Program Files (x86)\Common Files\Avid\Audio\Plug-Ins" and run it (as a .bat).
PS: the fixer will place the fixed plugins in "C:\Users\Public\modified" (just read the screen while executing, it gives you the new files path. If you want to move them to the right path, you can execute this from the new files path ("C:\Users\Public\modified")
for %%d IN (*.aaxplugin) do (mkdir "%%d_temp/Contents\x64" & move "%%d" "%%d_temp/Contents\x64/%%d" & rename "%%d_temp" "%%d")
with that, I iterate over every plugin and create a folder with the same name (I create _temp because of name colision, after moving the file I rename it to the correct one), also with the subfolder "/Contents/x64", and move the plugin inside. Once donde, you can just take the resulting folders and place them in their correct path.
Hope it works, for me it works like a charm.

Resources