- Windows Batch create folders based on file names
- 3 Answers 3
- Create folder with batch but only if it doesn’t already exist
- 9 Answers 9
- How to create a folder with name as current date in batch (.bat) files
- 25 Answers 25
- Create folder in batch script and ignore if it exists
- 2 Answers 2
- Windows batch command to create backup folder and replace folder
- 1 Answer 1
Windows Batch create folders based on file names
I want to create folders based on file names that look like this:
the tree should look like this
and the files within should keep their original name How can I address the last whitespace before each number? I can’t specify a fixed value for «tokens» because the position of the last whitespace varies from file to file. This was my approach:
-> ECHO to debug the result
3 Answers 3
You would need to change the setting of sourcedir to suit your circumstances.
The required MD commands are merely ECHO ed for testing purposes. After you’ve verified that the commands are correct, change ECHO(MD to MD to actually create the directories. Append 2>nul to suppress error messages (eg. when the directory already exists)
The required MOVE commands are merely ECHO ed for testing purposes. After you’ve verified that the commands are correct, change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved )
Simply generate the same name for the file and directory, trim off the last character from the name until that character is a space, trim that off and you have the required dirname and filename.
The idea behind the code is to iterate over the list of files and for each one, the spaces in it name are replaced with a backslash ( file\with\words\01 ) so we can use the for replaceable parameters to query the «parent folder» of the last element (the name without the ending numbers) and later replace the backslashes with spaces to get the final folder name.
The multiple setlocal/endlocal are included to handle the case of filenames that could include exclamation points (a problematic character when delayed expansion is enabled).
The code tries to move all matching files in each set with only one move command, but depending on the real names, it is possible that files from other set could also match. To avoid it, the line
should be converted into
so files are moved one by one without problems.
Create folder with batch but only if it doesn’t already exist
Can anybody tell me how to do the following in in a Windows batch script? ( *.bat ):
- Create a folder only if it doesn’t already exist
In more detail, I want to create a folder named VTS on the C:\ drive, but only if that folder doesn’t already exist. I don’t want to overwrite the contents of the folder if it already exists and the batch is executed.
9 Answers 9
You just use this: if not exist «C:\VTS\» mkdir C:\VTS it wll create a directory only if the folder does not exist.
Note that this existence test will return true only if VTS exists and is a directory. If it is not there, or is there as a file, the mkdir command will run, and should cause an error. You might want to check for whether VTS exists as a file as well.
Just call mkdir C:\VTS no matter what. It will simply report that the subdirectory already exists.
Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn’t care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn’t exist, and it doesn’t overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk’s answer.
How to create a folder with name as current date in batch (.bat) files
I don’t know much about windows .bat file syntax. My simple requirement is to create a folder at a specific location with name as current date. I tried searching this on google but didn’t get any good option. Is there any way to do this?
25 Answers 25
Try this (an equivalent of bash backquotes):
0,8% . You have other options too (character replacing, for example) but if you need a portable solution you should go with PowerShell. Hope this helps! – Adriano Repetti Mar 3 ’15 at 8:16
-10,2% – Delmonte Sep 21 ’16 at 14:37
Quick and dirty: If you can live with the date being UTC instead of local, you can use:
Works in all locales. Only on XP and higher, though.
You need to get rid of the ‘/’ characters in the date before you can use it in mkdir like this:
If you want mm-dd-yyyy format you can use:
0,2% (tested on german Win10) – PeterCo Aug 14 ’17 at 9:34
This depends on the regional settings of the computer, so first check the output of the date using the command prompt or by doing an echo of date.
To do so, create a batch file and add the below content
It produces an output, in my case it shows Fri 05/06/2015.
Now we need to get rid of the slash (/)
For that include the below code in the batch file.
if you echo the «temp», you can see the date without the slash in it.
Now all you need to do is formatting the date in the way you want.
For example I need the date in the format of YYYYMMDD, then I need to set the dirname as below
To explain how this works, we need to compare the value of temp
now position each characters with numbers starting with 0.
So for the date format which I need is 20150605,
The Year 2015, in which 2 is in the 8th position, so from 8th position till 4 places, it will make 2015.
The month 06, in which 0 is in the 6th position, so from 6th position till 2 places, it will make 06.
The day 05, in which 0 is in the 4th position, so from 4th position till 2 places, it will make 05.
So finally to set up the final format, we have the below.
To enhance this date format with «-» or «_» in between the date, month and year , you can modify with below
So the final batch code will be
The directory will be created at the place where this batch executes.
Create folder in batch script and ignore if it exists
How do I create folder(and any subfolders) in batch script? What is important, if folder(or any subfolders) already exists, it should not return error.
For example, something like this:
- mkdir mydir — success(directory is now created)
- mkdir mydir\subdir — success(now mydir contains subdir )
- mkdir mydir — success(folder already exists, should not throw an error)
- mkdir mydir\subdir — success(folders already exists, should not throw an error)
What I actually need is just to ensure that folders structure exists.
2 Answers 2
A standard method to create a directory structure is:
By default command extensions are enabled and delayed expansion is disabled. The batch code above explicitly sets up this environment.
The command MD creates the complete directory structure to specified directory with enabled command extensions.
MD outputs an error if the directory already exists. This might be useful to inform a user entering the command manually about a possible mistake in entered directory path as it could be that the user wanted to create a new directory and has entered just by mistake the name of an already existing directory.
But for scripted usage of command MD it is often a problem that this command outputs an error message if the directory to create already exists. It would be really helpful if command MD would have an option to not output an error message in case of directory to create already existing and exiting with return code 0 in this case. But there is no such option.
The solution above creates the directory and suppresses a perhaps output error message with redirecting it from handle STDERR to device NUL.
But the creation of the directory could fail because of invalid character in directory path, drive not available (on using full path), there is anywhere in path a file with name of a specified directory, NTFS permissions don’t permit creation of the directory, etc.
So it is advisable to verify if the directory really exists which is done with:
It is important that the directory path ends now with \* or at least with a backslash. Otherwise it could be possible for the example that there is a file with name subdir 2 in directory mydir\subdir 1 which on usage of the condition if not exist «%Directory%» would evaluate to false although there is no directory subdir 2 .
It is of course also possible to do the directory check first and create the directory if not already existing.
The user can see now the error message output by command MD if the directory structure could not be created explaining briefly the reason.
This batch code could be written more compact using operator || :
For details about the operators || and & read the answer on Single line with multiple commands using Windows batch file.
The command ENDLOCAL is not used before goto :EOF because this command requires also enabled command extensions. Windows command interpreter executes this command implicit on leaving execution of the batch file.
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.
Read also the Microsoft article about Using Command Redirection Operators.
Windows batch command to create backup folder and replace folder
I need to backup an existing folder with date-time stamp and replace it (delete and recreate) with new content inside the folder.
Does anyone have a script to do this?
I tried the following code, where %ApplicationDeploymentFolderPath% = \\servername\foldername
1 Answer 1
The command date with parameter /T outputs the current date in format defined by configured country for current user account. Exactly the same date string can be accessed by referencing dynamic environment variable DATE for example with %DATE% .
The command time with parameter /T outputs the current time in format defined by configured country for current user account. Exactly the same time string can be accessed by referencing dynamic environment variable TIME for example with %TIME% .
What happens on execution of this command line?
for respectively cmd.exe processing the batch file starts in background one more command process using %ComSpec% /c with the command line between ‘ . So executed in background is following with Windows installed in C:\Windows :
The output of command date to handle STDOUT of this command process in background is captured by FOR respectively Windows command processor instance executing the batch file.
The captured line is split up into three substrings using / as string delimiter assigned to the loop variables a , b and c which are concatenated together in reverse order with underscore as delimiter.
This task can be done much faster by replacing ‘date /t’ by «%DATE%» . In this case FOR processes the date string expanded by already running cmd.exe on parsing this command line before executing FOR. So there is no starting of one more cmd.exe in background and capturing its output just to process the same date string which makes batch file execution a bit faster.
The same is true for ‘time /t’ which can be replaced by «%TIME%» .
But the two FOR loops could be completely optimized away by using string substitution as described for example by answer on What does %date:
3,2% mean? and region dependent date and time format is well known for example by running in a command prompt window:
This command outputs on my computer with German date/time format according to configured country:
It can be seen on this output that the original code would not work on my Windows computer with my account because of date string contains . and not / and time string contains a comma.
So better would be using a region independent solution as explained very detailed in answer on Why does %date% produce a different result in batch file executed as scheduled task? The disadvantage is that execution of wmic.exe takes much longer than cmd.exe needs to reformat date and time string to yyyy_MM_dd_HHmm . However, the batch file is executed most likely not very often per day, and so it does not really matter if execution to get date/time in this format takes some milliseconds or about one second.
Copying the entire folder is not really necessary in this case. It should be enough to rename it with:
The command move could be also used if command ren cannot be used for unknown reasons.
However, the main problem is missing knowledge about how and when to use delayed expansion. Open a command prompt, run set /? and read the output help explaining on an IF and a FOR example delayed environment variable expansion.
The issue here is that backup_folder is not defined on executing the command lines referencing it with %backup_folder% because of all occurrences of %variable% are replaced by Windows command processor already on parsing entire command block starting here with ( on IF condition at top by current value of the referenced environment variable before executing the command IF.
So executed on existing release folder is:
The solution is here avoiding the command block by changing the first IF condition.
Fast region dependent solution:
Slower region independent solution:
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.
- echo /?
- endlocal /?
- for /?
- goto /?
- if /?
- md /?
- ren /?
- set /?
- setlocal /?
- wmic /?
- wmic os /?
- wmic os get /?
- wmic os get localdatetime /?