Guys I am trying to write a batch file that kills all files within a directory - basically every file will have 'status' within it
I cant just kill the files on file extension either - there is this post
batch script delete file containining certain chars
however, this does not seem to do it
for /f "delims=" %%a in ('
findstr /l /i /m /c:"status" "c:\somewhere\*.*"
') do echo del "%%a"
This uses findstr to list the files (/m) containing the literal (/l) "status" ignoring the string case (/i). The list is processed with a for /f command to execute the del operation for each file.
del commands are only echoed to console. If the output is correct, remove the echo command.
edited if the string status is not inside the file but in the file name, the code is reduced to
del "c:\somewhere\*status*"
Related
Been trying to create an additional batch script that processes files for me. I either get send 1 or several .pdf test files in a .rar file.
So what I am trying to aim for is:
If the first variable 1 is named 'test' then
Is there a .rar file in the folder from variable 2 then
Extract to a folder and then delete .rar file
else
check that there is a .pdf file and then copy to folder
Else
Tell the user that neither a file or a archive has been found
I've managed to scrape this together but I need help trying to expand it further to include all the options:
#echo off
set "cat=%1"
IF "%cat%"=="test" ( for /f %%G in ('dir *.rar /b') do set filename=%%~G)
echo %filename%
This only gives me half the file name as they have gaps in the filename, also need to change the dir in the 3rd line to be looking in variable 2 that is sent in.
To add to it I've just been told that it's the same for .txt files, the multiples are sent to me in a .rar file
I suggest to open a command prompt, run call /? and read the output help. The help explains how the arguments – also called options or parameters, but not variables – of a batch file can be referenced from within a batch file.
It is advisable to check if a batch file is called with at least one argument if it must be called with at least one argument and output a help for correct usage of the batch file if it was started without any argument or if it was started with /? which is the default on Windows to get help about a command or program.
The manual for console version of WinRAR is the file Rar.txt in program files folder of WinRAR. It can be read in this text file after opening it with a double click that Rar.exe can extract one or more *.rar archive files found in a directory. For that reason it is not really necessary to use command FOR. But it is advisable for this task to use command FOR as the RAR file(s) should be deleted after successful extraction of the RAR archive(s).
Let us look on the FOR command line for /f %%G in ('dir *.rar /b') do and what it does on execution.
FOR with option /F to process a text file content or a single string or the output of a command line results in this case in starting a command process in background with %ComSpec% /c and the command line between the two ' appended. So executed by the Windows command process cmd.exe processing the batch file with for /F is the following with Windows installed into C:\Windows as by default:
C:\Windows\System32\cmd.exe /c dir *.rar /b
The command DIR executed by separate command process in background
searches in current directory
for directory entries (files or directories)
matching the wildcard pattern *.rar
and not having hidden attribute set (implicit default is /A-H on option /A not specified at all)
and outputs to handle STDOUT the found directory entries matching the criteria above in bare format line by line which means with just file/folder name without path and never enclosed in double quotes even on containing a space or one of these characters &()[]{}^=;!'+,`~.
An error message is output by DIR to handle STDERR of background command process if it cannot find any directory entry matching the search criteria.
FOR respectively the command process processing the batch file redirects the output to handle STDERR of the background command process to its own STDERR handle which results in getting it displayed in console window in this case. But the output to handle STDOUT of started background command process is captured by FOR respectively the command process processing the batch file and is processed line by line after started background command process terminated itself.
FOR used with option /F always ignores empty lines. This does not matter here because of DIR does not output empty lines on being executed with option /B.
for /F splits up a non-empty line by default into substrings using normal space and horizontal tab as string delimiters and assigns by default just first space/tab separated string to the specified loop variable which is here the loop variable G. for /F ignores by default additionally also a processed line if the first substring after splitting the line up starts with a semicolon because of eol=; is the default for end of line option.
So the command line for /f %%G in ('dir *.rar /b') do causes several problems on processing the list of directory entries output by DIR.
For a file/folder name containing a space just the first space/tab separated part of the file/folder name is assigned to loop variable G instead of complete name. For example a name like My Archive.rar results in just My is assigned to the loop variable G.
A file/folder name with one or more leading spaces is assigned to loop variable G without those leading spaces which means again that G does not hold complete name. For example a name like TwoLeadingSpaces.rar results in getting assigned to loop variable G just TwoLeadingSpaces.rar without the two leading spaces and the file (or folder) is not found on referencing the value of loop variable G.
A file/folder name with a semicolon at beginning after zero or more leading spaces is completely ignored by command FOR for further processing. For example names like ;Test.rar (name beginning with a semicolon) or ;TestWithALeadingSpace.rar (name with leading space and a semicolon) are completely ignored for further processing by FOR.
The points 2 and 3 are usually no problem as file/folder names with leading space(s) or a semicolon at beginning are really very rare. But a file/folder name with a space occurs very often.
A solution would be using FOR without option /F:
for %%G in (*.rar) do
FOR searches now itself for non-hidden files (not directories) in the current directory matching the wildcard pattern *.rar and assigns a found file name without path to loop variable G and next runs the command(s) after do. There is no additional command process started and there is no substring splitting done.
But there is a problem with this very simple solution in case of the commands executed for each found file name delete, move or rename files matched by the wildcard pattern *.rar. The list of directory entries matching the wildcard pattern changes on each iteration of the body of the FOR loop while command FOR queries the directory entries one after the other with executing the commands between each directory query. This is especially on FAT16, FAT32 and exFAT drives a real problem, but can result also in unexpected behavior on NTFS drives.
Whenever a FOR loop is used to process a list of files which could change during the iterations of the loop because of deleting, moving or renaming the files matched by a wildcard pattern, it is better to process a list of files loaded completely into memory before first iteration of the loop.
So a better solution for this task with the requirement to delete a RAR archive file after successful extraction is:
for /F "eol=| delims=" %%I in ('dir *.rar /A-D /B 2^>nul') do
The DIR option /A-D results in ignoring directory entries with attribute directory. So output by DIR are just file names matching the wildcard pattern in current directory including hidden RAR archive files.
2^>nul is passed as 2>nul to the background command process which results in redirecting the error message output by DIR on no *.rar file found to device NUL to suppress it.
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 the embedded dir command line with using a separate command process started in background.
The for /F option eol=| changes the end of line character from ; to |. No file name can have a vertical bar in its file name according to Microsoft documentation about Naming Files, Paths, and Namespaces. So no file name is ignored anymore by FOR because of end of file option.
The for /F option delims= changes the delimiters list for line splitting into substrings to an empty list of delimiters which disables the line splitting behavior completely. So a file name with one or more spaces anywhere in file name is assigned completely to the specified loop variable I.
The task description is not very clear regarding to what to do depending on the batch file arguments, especially if the first argument is not case-insensitive test.
However, the following commented batch file could be working for this task on being called with first argument being test or with no arguments at all or with /? as first argument.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if "%~1" == "" goto OutputHelp
if "%~1" == "/?" goto OutputHelp
if /I not "%~1" == "test" goto MoreCode
set "SourceFolder=%~2"
if defined SourceFolder goto CheckFolder
echo/
echo Error: Folder with RAR or PDF file(s) not specified on command line.
goto OutputHelp
:CheckFolder
rem Replace all forward slashes by backslashes in folder name.
set "SourceFolder=%SourceFolder:/=\%"
rem Append a backslash to folder path if it does not end with a backslash.
if not "%SourceFolder:~-1%" == "\" set "SourceFolder=%SourceFolder%\"
rem Check the existence of the source folder.
if exist "%SourceFolder%" goto ProcessFolder
echo/
echo Error: Folder "%SourceFolder%" does not exist.
goto OutputHelp
:ProcessFolder
rem Get full qualidfied folder name, i.e. the folder name
rem with its absolute path and ending with a backslash.
for %%I in ("%SourceFolder%") do set "SourceFolder=%%~fI"
rem Define the destination folder for the PDF files extracted from the
rem RAR archive file(s) in source folder or copied from source folder.
set "DestinationFolder=C:\Temp\Test\"
rem Search for all *.rar files in folder passed with second argument and
rem extract all *.pdf files in each RAR archive file to the configured
rem destination folder. Rar.exe creates the destination folder automatically
rem if it is not already existing. The batch file is halted after processing
rem a RAR file on which Rar.exe exited with a value greater 0. Read the exit
rem codes documentation of Rar.exe at bottom of text file Rar.txt for more
rem information about the RAR exit codes. See Rar.txt also for the meaning
rem of the few RAR switches used here.
set "RarFileCount=0"
for /F "eol=| delims=" %%I in ('dir "%SourceFolder%*.rar" /A-D /B 2^>nul') do (
set /A RarFileCount+=1
"%ProgramFiles%\WinRAR\Rar.exe" e -cfg- -idcdp -or -- "%SourceFolder%%%I" *.pdf "%DestinationFolder%"
if not errorlevel 1 (del /A /F "%SourceFolder%%%I") else echo/& pause
)
if %RarFileCount% == 0 goto CheckFiles
if %RarFileCount% == 1 (set "PluralS=") else set "PluralS=s"
echo/
echo Info: Processed %RarFileCount% *.rar file%PluralS% in folder "%SourceFolder%".
goto EndBatch
:CheckFiles
echo Info: There are no *.rar files in folder "%SourceFolder%".
if exist "%SourceFolder%*.pdf" goto CopyFiles
echo Info: There are no *.pdf files in folder "%SourceFolder%".
goto EndBatch
:CopyFiles
rem Copy all PDF files in source folder to destination folder. xcopy.exe
rem creates destination folder automatically if it is not already existing.
echo/
%SystemRoot%\System32\xcopy.exe "%SourceFolder%*.pdf" "%DestinationFolder%" /C /I /Y
goto EndBatch
:OutputHelp
echo/
echo Usage: %~n0 [TEST] [Folder with RAR or PDF file(s)]
echo/
echo If the first argument is case-insensitive TEST, the second argument
echo specifies the folder containing the RAR files to extract or the PDF
echo files to copy to destination folder. The folder must be specified
echo with first argument being TEST.
echo/
pause
goto EndBatch
:MoreCode
rem Add here the code to execute on first argument is not case-insensitive TEST.
:EndBatch
endlocal
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 /?
del /?
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
pause /?
rem /?
set /?
setlocal /?
xcopy /?
"%ProgramFiles%\WinRAR\Rar.exe" /?
You can use this:
#echo off
set "cat=%~1"
IF "%cat%"=="test" (
for %%G in (*.rar) do set filename=%%G
)
echo %filename%
Here wildcard is used to get all the rar files in the directory.
I have a batch-file which works as intended, deleting files with a specified string or extension, but I want to keep a record of what was deleted.
I want to take the output of the command and write it to a .txt file on my desktop before running the actual command:
if /I %CONFIRM%==y (
(del /F /S %FOLDER%\*%DELETE%)>"C:\Users\%username%\Desktop\deleted.txt"
del /F /S %FOLDER%\*%DELETE%
)
In this case %DELETE% is the user input variable value bak.
If I try to delete .bak files it still deletes the files but gives me the following result and wont write to text file:
Could Not Find C:\Users\USERXYZ\Desktop\*bak
Any ideas?
Perhaps
set /p "confirm=delete %FOLDER%\*%DELETE% ? "
if /I %CONFIRM%==y (
(ECHO del /F /S %FOLDER%\*%DELETE%)>"C:\Users\%username%\Desktop\deleted.txt"
(dir/S/B %FOLDER%\*%DELETE%)>>"C:\Users\%username%\Desktop\deleted.txt"
del /F /S %FOLDER%\*%DELETE%
)
may assist.
In your code, the first del command deletes the file AND should create the deleted.txt file containing the names of the deleted files. Since those files have now been deleted, then the second del command quite correctly reports that it could not delete the files since they are no longer there.
Note that > will create a NEW file, whereas >> will append to an existing file (or create a new file if none already exists)
The echo del in this code shows the command that is about to be executed - you may or may not want this - idk. However the > puts this into a NEW file.
Does anyone know how to replace first space in a file name by a text like _TEMP- after the first 8 characters of the file name?
Also I was hoping to write a batch file that can change multiple files in a directory with similar file name structure.
For example:
Before: 12345678 Hello World.txt
After: 12345678_TEMP-Hello World.txt
Here is a simple code demonstrating usage of FOR for this task:
#echo off
set "FileName=12345678 Hello World.txt"
for /F "tokens=1*" %%I in ("%FileName%") do echo ren "%FileName%" "%%I_TEMP-%%J"
set "FileName="
echo/
pause
The file name is assigned here to an environment variable.
The command FOR with option /F splits the file name string specified in double quotes up into substrings using the default delimiters space and horizontal tab.
With tokens=1* is defined that first space/tab delimited string is assigned to specified loop variable I. The asterisk is responsible for not further splitting up on spaces/tabs after first string and instead assign everything after space(s)/tab(s) after first string to next loop variable which is according to ASCII table the loop variable J. So for this example I gets assigned 12345678 and J gets assigned Hello World.txt
The command to execute is here ECHO which prints the command line for renaming the file which would be executed without echo.
Another batch code which renames all non hidden files in current directory with a space in file name not containing already _TEMP- in file name:
#echo off
for /F "eol=| delims=" %%# in ('dir "* *" /A-D-H /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /L /V /C:_TEMP- 2^>nul') do (
for /F "tokens=1*" %%I in ("%%#") do ren "%%#" "%%I_TEMP-%%J"
)
The outer FOR executes in a separate command process started with cmd.exe /C in background the command line:
dir "* *" /A-D-H /B 2>nul | C:\Windows\System32\findstr.exe /L /V /C:_TEMP- 2>nul
DIR searches in current directory because of /A-D-H (attribute not directory and not hidden) just for non hidden files matching the wildcard pattern * * and outputs just the found file names because of /B (bare format). An error message in case of no file matching these criteria is suppressed by redirecting the error message written to handle STDERR to the device NUL.
The file names output by DIR to handle STDOUT are redirected to STDIN of command FINDSTR which searches in the list of file names case-sensitive and literally for the string _TEMP-. But output are not the lines containing this string, but the inverted result because of /V. So output are by FINDSTR to handle STDOUT all lines not containing the string _TEMP-. A possible error message output by FINDSTR to handle STDERR is suppressed by redirecting it to device NUL.
The outer FOR captures the output to STDOUT of background command process and then processes the captured output line by line. It is very important here to process a captured list of file names because the found files to modify in current directory are renamed by the command inside the FOR loop. Otherwise on using FOR itself to find files matching wildcard pattern * * it could happen that a renamed file is processed multiple times or some files are skipped because of list of files in current directory changes during loop execution.
Empty lines are always ignored by FOR, but the list of file names does not contain empty lines.
for /F would also ignore lines starting with a semicolon by default. This behavior is changed by specifying eol=| to skip lines starting with a vertical bar. File names can begin with a semicolon, but file names cannot contain a vertical bar. So it is made sure not skipping any file name with eol=|.
for /F with default options would split a line (file name) up on spaces/tabs and would assign just first substring to specified loop variable #. This behavior is not good here because the complete file name from filtered output of DIR is needed for the file renaming task. For that reason delims= is used specifying an empty list of delimiters resulting in no splitting up the line (file name) into substrings (tokens).
It could be that a file is named for example 12345678 Hello World.txt with multiple spaces in series in file name. This is the reason for first getting assigned to loop variable # the complete file name as found by DIR in current directory.
The file name is split up into two substrings as explained above and then renamed which is successful if there is not already a file or folder with new name in current directory and the file to rename is not opened currently by an application with sharing access denied.
The batch file above could be coded also with a single command line in batch file:
#for /F "eol=| tokens=1*" %%I in ('dir "* *" /A-D-H /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /L /V /C:_TEMP- 2^>nul') do #ren "%%I %%J" "%%I_TEMP-%%J"
Or the single command line is really executed directly in a command prompt window as follows with just one percent sign on referencing the loop variables I and J:
for /F "eol=| tokens=1*" %I in ('dir "* *" /A-D-H /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /L /V /C:_TEMP- 2^>nul') do #ren "%I %J" "%I_TEMP-%J"
But this single command line version works only for files with always a single space character between first part and remaining part of file name, i.e. it works for 12345678 Hello World.txt but does not work for 12345678 Hello World.txt.
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 /?
findstr /?
for /?
pause /?
ren /?
set /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and |. The redirection operators > and | must be escaped with caret character ^ on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.
Here's a possible batch file solution for replacing the 9th character with your given string, _TEMP-; it utilises PowerShell:
#Echo Off
Set "SD=%UserProfile%\Documents"
PowerShell -C "GI '%SD%\???????? *.txt'|Ren -N {$_.BaseName.Remove(8,1).Insert(8,'_TEMP-')+$_.Extension} -Wh"
Pause
Just change %UserProfile%\Documents on line 2 to the folder containing the .txt files, (if they're not really .txt files either, change txt on line 3 to the appropriate string or wildcard. If the string you wish to add is also different, please replace _TEMP- on line 3 with your desired string too). The script is currently designed to show you what would happen, were the files to be renamed; if you're happy with the output, change the script thus:
#Echo Off
Set "SD=%UserProfile%\Documents"
PowerShell -C "GI '%SD%\???????? *.txt'|Ren -N {$_.BaseName.Remove(8,1).Insert(8,'_TEMP-')+$_.Extension}"
If you didn't want to remove the space after those 8 characters, then:
#Echo Off
Set "SD=%UserProfile%\Documents"
PowerShell -C "GI '%SD%\???????? *.txt'|Ren -N {$_.BaseName.Insert(8,'_TEMP-')+$_.Extension} -Wh"
Pause
…and similarly if you're happy with the output, change the script to this:
#Echo Off
Set "SD=%UserProfile%\Documents"
PowerShell -C "GI '%SD%\???????? *.txt'|Ren -N {$_.BaseName.Insert(8,'_TEMP-')+$_.Extension}"
I'm sure there will be better ways of doing this, even with PowerShell, but given that your provided information is lacking, I'm unable to suggest anything else at this time.
I'm making a simple batch script to process a large set of files and delete all I don't want. I want about 10% of the files and they all have certain tags in their names, lets say they contain apple, orange or pear. As there are so many files I want deleted, it would be quite time consuming to construct a FOR loop such as:
#echo off
pause
for /R %%i in ([the list of names of the files I don't want]) do del %%i
pause
So I was wondering if it is possible to code it such that it deletes all files which don't have names containing apple, orange or pear?
In other words all files should be deleted not containing in its name one of those 3 words.
I'm using a FOR loop because the files are nested within lots of subdirectories and I would like to preserve this structure after the unwanted files have been deleted.
You can use this batch file containing (more or less) just one command line:
#echo off
for /F "delims=" %%I in ('dir * /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /R /V /C:"apple[^\\]*$" /C:"orange[^\\]*$" /C:"pear[^\\]*$"') do ECHO del "%%I"
This batch code does not really delete files because of command ECHO before del at end of the command line. Run this batch file from within a command prompt window with current directory being the root of the directory tree on which to delete unwanted files and verify the output. Then remove ECHO and run the batch file once again.
The command DIR searches because of /S in current directory and all subdirectories only for files because of /A-D (not directory attribute) matching the wildcard pattern * with output in bare format because of /B which means the output contains just the names of all found files with full path.
DIR outputs an error message to handle STDERR if it can't find any file. This error message is suppressed by redirecting it to device NUL with 2>nul. The redirection operator > must be escaped here with caret character ^ to be first interpreted as literal character on parsing the FOR command line by Windows command interpreter.
The output of DIR to handle STDOUT is piped with | to standard console application FINDSTR which searches in all lines case-insensitive because of /I for the regular expression strings because of /R specified with /C:. The redirection operator | must be escaped here also with ^.
An OR expression is not supported by FINDSTR like it is by other applications with regular expression support. But it is possible to specify multiple search strings as done here which are all applied on each line of the text to process one after the other until a positive match occurs or there is no more search string. That is a classic OR.
The regular expression word[^\\]*$ means:
word ... There must be found word (case-insensitive).
[^\\]* ... Find 0 or more characters NOT being a backslash.
$ ... The matching string must be found at end of line.
The regular expression is used to get a positive match only for lines on which the file name contains either apple OR orange OR pear, but NOT the file path.
But there is one more FINDSTR option: /V. This option inverts the result output to handle STDOUT. So output are the lines on which none of the 3 regular expressions produce a positive match.
The command FOR processes each line output by FINDSTR used as negative filter for output of DIR and runs for each line the command DEL respectively ECHO without splitting the line up into space/tab separated strings because of delims=.
And that's it.
It is necessary to prevent the batch file from deletion if being stored in the directory tree processed by command DIR. This can be achieved most easily with setting read-only attribute on batch file as command DEL does not delete files with read-only attribute set.
Example:
#echo off
rem Prevent batch file from deletion by setting read-only attribute on batch file.
%SystemRoot%\System32\attrib.exe +r "%~f0"
for /F "delims=" %%I in ('dir * /A-D /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /R /V /C:"apple[^\\]*$" /C:"orange[^\\]*$" /C:"pear[^\\]*$"') do del "%%I"
rem It is safe to remove read-only attribute from batch file.
%SystemRoot%\System32\attrib.exe -r "%~f0"
The batch code above has no ECHO before command del and therefore really deletes files on execution.
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.
attrib /?
del /?
dir /?
echo /?
findstr /?
for /?
rem /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of | and 2>nul.
I created the following batch script to create a folder based on today's date and then group files into folders based on the file name.
For example the files
JIM_BRICKMAN_QPS.avi
JIM_BRICKMAN_Slice.avi
JIM_BRICKMAN_Slice.jpg
are moved to the folder BRICKMAN.
This works fine, however, attempts to modify the batch file to move the newly created folders into the newly created date folder fail or overwrite the folders when going through the loop.
for /F "tokens=1-4 delims=/" %%A in ('date /t') do (
set DateDay=%%A
set DateMonth=%%B
set DateYear=%%C
)
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
if not exist "%CurrentDate%" md %CurrentDate%
for %%A in (*.avi *.jpg) do (
for /f "tokens=1,* delims=_" %%D in ("%%~nA") do (
md "%%D" 2>nul
echo Moving file %%A to folder %%D
move "%%A" "%%D" >nul
)
)
echo Finished
Additionally, I can't seem to get the token to ignore the first delimiter so that the folder is titled JIM_BRICKMAN and not just BRICKMAN.
EDIT:
I rewrote the batch file after the suggestions in the comments:
set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
if not exist "%CurrentDate%" md %CurrentDate%
for %%A in (*.avi *.jpg) do (
for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (
md "%%D_%%E" 2>nul
move "%%A" "%%D_%%E" >nul
)
)
But the script seems to bomb out. I tried to capture the error, but it closes despite me putting PAUSE in the script.
Double clicking on a batch file in development is no good idea because this results in starting
%SystemRoot%\System32\cmd.exe /c "batch file name with full path and extension"
As it can be read on running cmd /? from within a command prompt window, the option /C means close the command process and its console window immediately after execution of command, executable or script finished independent on the reason for ending the execution.
For debugging a batch file in development it is much better to
open a command prompt window,
change the current directory with command CD to directory of batch file and
run the batch file by typing its name and hitting key RETURN or ENTER.
For batch files which should work independent on which directory is the current directory, it is advisable to omit point 2 and run the batch file with entering its full path, file name and file extension enclosed in double quotes with current directory being not the directory of the batch file.
A batch file is executed from within a command prompt window with:
%SystemRoot%\System32\cmd.exe /K BatchFileNameAsTyped
The option /K means keep command process running which results in keeping also command prompt window opened after execution of command/executable/script which makes it possible to read error messages.
The keys UP ARROW and DOWN ARROW can be used to reload command lines once entered in command prompt window making it easy to run the batch file once again after making a modification in GUI text editor.
And with having #echo off removed from first line of batch file, or changed to #echo ON, or commented out this line with command REM or with :: (invalid label) at beginning, it is also possible to see which lines Windows command interpreter really executes after applying immediate environment variable expansion and where an error occurs in case of a syntax error.
Wrong on second batch code is the line:
for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (
Specified as loop variable must be always 1 character. Right would be:
for /f "tokens=1,2 delims=_" %%D in ("%%~nA") do (
The command echo %DATE% outputs on my computer with my account and my region settings today the date 01.04.2017.
The command echo %DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4% outputs 01-04-2017.
So this part of the script works.
Hint: A list of directories in format YYYY-MM-DD is better than in format DD-MM-YYYY. The list of directories with format YYYY-MM-DD sorted alphabetically as by default is automatically with this date format also sorted from oldest to newest. Date format DD-MM-YYYY results in a weird list of the directories on being sorted alphabetically as by default.
A batch file for this task could be:
#echo off
set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
for %%A in (*.avi *.jpg) do (
for /F "tokens=1,2 delims=_" %%D in ("%%~nA") do (
if not "%%E" == "" (
md "%CurrentDate%\%%D_%%E" 2>nul
move /Y "%%A" "%CurrentDate%\%%D_%%E\"
) else (
md "%CurrentDate%\%%D" 2>nul
move /Y "%%A" "%CurrentDate%\%%D\"
)
)
)
set "CurrentDate="
How the inner loop works is most interesting for this task.
for /F and "%%~nA" means the command FOR should process just the file name of the *.avi or *.jpg file without file extension found by outer FOR loop.
delims=_ means the FOR command should split up the string into multiple parts (tokens) using underscore as delimiter. The first file name is JIM_BRICKMAN_QPS which would be split up to:
JIM assigned to loop variable D being specified in FOR command line,
BRICKMAN assigned to loop variable E which is the next character in ASCII table after D and
QPS assigned to loop variable F.
This string split feature is the reason why loop variables are interpreted case-sensitive while environment variables are interpreted not case-sensitive.
With tokens=1,2 is specified that just first and second string parts are of interest. So inner FOR can stop string splitting after having already determined the first two underscore delimited strings and having assigned them to the loop variables D and E.
FOR executes the command block if it could determine at least 1 string delimited by an underscore. So it is possible that loop variable D has a string value, but loop variable E is an empty string, for example if the file name does not contain any underscore. That is the reason for the IF condition.
The command MD creates with command extensions enabled as by default the entire directory tree. Therefore it is not necessary to create the date subdirectory explicitly before searching for *.avi and *.jpg files. That is good as it avoids creating empty date directories when there are no *.avi and *.jpg files in current directory.
As the *.avi and *.jpg files in current directory should be moved to DD-MM-YYYY\Token1_Token2 it is of course necessary to specify also the environment variable with todays date string on creating the directory and moving the file.
The error message output by MD if the directory exists (or when it fails to create the directory because of missing permissions) to handle STDERR is redirected with 2>nul to device NUL to suppress it.
The MOVE command is used with option /Y to move the file to target folder even if the current file exists already in target folder.
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 /?
for /?
if /?
md /?
move /?
set /?
Read also the Microsoft article about Using Command Redirection Operators.