Passing a Variable to Subfolder - batch-file

I'm a bit stuck here.
Running a batch file that has a couple of steps.
I need to run a batch file in a folder go through each folder and 3 folders down assign that a variable. So copy that 3rd folder down in each folder
So my folder structure
e.g1: 2135698563325\Folder1\Folder2\Folder3\c007
eg2: 21356486543248\Folder1\Folder2\Folder3\c111
REM get c007 as a variable to be able to set a folder name
set variable = Folder0\Folder1\Folder2\Folder3\%Variable%
REM Step 2:Check that the c007 folder doens't already exist
if %Variable%==\\hippo\Folder4\ ((echo "Error: Duplicate Folder"):eof) Else mkdir \\hippo\Folder4\%Variable%
REM Step 3:Copy a default File Structure from Template Dir
xCopy /s \\hippo\production\Folder4\Temaplate \\hippo\production\Folder4\%Variable%
Rem Step 4: Copy the contents of c007 in to Folder6
xCopy /s %Variable% \\hippo\production\Folder4\Variable\Folder5\Folder6\
Does this make more sense?

Here is a comment batch script on how to get c007 and c111. Put your code into the subroutine ProcessFolder. The folder names c007 and c111 are passed to the subroutine via first argument referenced with %~1.
#echo off
setlocal EnableExtensions
rem Get current directory path always without backslash at end. Environment
rem variable CD holds the current directory path usually without backslash
rem at end. But current directory string is with backslash at end if the
rem current directory is the root directory of a drive.
if "%CD:~-1%" == "\" (
set "CurrentFolder=%CD:~0,-1%"
) else (
set "CurrentFolder=%CD%"
)
rem Process the folder names 4 levels below current directory.
for /D %%A in ("%CurrentFolder%\*") do (
for /D %%B in ("%%A\*") do (
for /D %%C in ("%%B\*") do (
for /D %%D in ("%%C\*") do (
for /D %%E in ("%%D\*") do (
call :ProcessFolder "%%~nxE"
)
)
)
)
)
endlocal
rem Avoid a fall through to the subroutine by exiting batch processing here.
goto :EOF
rem Subroutine to process the folder with name found above.
:ProcessFolder
echo Folder variable is: %~1
rem Exit subroutine and continue in the most inner FOR loop above.
goto :EOF
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 /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?

Related

get two recent files from a folder in a batch script

I am trying to write a batch script that gets two recent files based on creation time from a given directory. In this batch script i want to invoke an .exe file that takes these two files as arguments.
Can someone please help me with this.
dir /a:-d-s /b /o:-d /t:c
This is the command i used that would list the names of the files in descending order based on the creation time. The command prints the result to the console but i want to assign it to some variable or array and access the top two filenames.
The following example is intended to set the two topmost returned files as 'array type' variables %Newest[1]% and %Newest[2]%
#For /F "Delims==" %%A In ('Set Newest[ 2^>NUL')Do #Set "%%A="
#For /F "Tokens=1*Delims=:" %%A In ('Dir /B/A-D-S/O-D/TC 2^>NUL^|FindStr /N "^"'
)Do #If %%A LEq 2 (Set "Newest[%%A]=%%B")Else GoTo Next
:Next
#Set Newest[ 2>NUL&&Pause
The last line was included just to show you any variables created from the loop. You would obviously replace this line with your own code, or leave it as is, and place your code beneath it. If you want to use the most recently modified date and time stamps instead of created, replace /TC with /TW on line 2
Off-topic:
Here's an example of it in use, based upon your later posted question, since deleted:
#Echo Off
For /F "Delims==" %%A In ('Set Newest 2^>NUL')Do Set "%%A="
For /F "Tokens=1-2*Delims=:" %%A In ('Dir /B/A-D-S/O-D/TC "Checkpoints" 2^>NUL^
^|FindStr /N "^"')Do If %%A LEq 2 (Set "Newest%%A=%%B")Else GoTo Next
:Next
Set "DT1="&For /F "Tokens=1*Delims=_" %%A In ('Set Newest 2^>NUL'
)Do If Not Defined DT1 (Set "DT1=%%~nB")Else Set "DT2=%%~nB"
If Not Defined DT1 Exit /B
Set "Target=Differences\Difference_%DT1%_%DT2%.csv"
Set Newest 2>NUL
Set Target 2>NUL
If Not Exist "Differences\" MD "Differences"
Pause
Here is a commented batch file for this task.
#echo off
rem Set up a local environment for this batch file with enabled command
rem extensions as required for command FOR and with disabled delayed
rem environment variable expansion to process also correct file names
rem with one or more exclamation marks in name.
setlocal EnableExtensions DisableDelayedExpansion
rem Make directory of the batch file the current directory.
rem It is possible to use any other directory on replacing
rem %~dp0 by a directory path.
pushd "%~dp0"
rem Make sure the environment variable File1 is not defined.
set "File1="
rem Get a list of files without system attribute in current directory
rem ordered by creation date with newest first and oldest last and process
rem this list of file names line by line with ignoring the batch file. The
rem loop processing the file names is exited after having assigned second
rem newest created file in this directory to the environment variable File2
rem in addition to newest file assigned to environment variable File1 with
rem a jump to the command line below the line with label RunProgram.
for /F "eol=| delims=" %%I in ('dir /A-D-S /B /O-D /TC 2^>nul') do (
if not "%%I" == "%~nx0" (
if not defined File1 (
set "File1=%%I"
) else (
set "File2=%%I"
goto RunProgram
)
)
)
rem There is no file or just one file found in current directory other
rem than this batch file and so the program cannot be executed at all.
goto EndBatch
rem Run the program with the file names of the two newest
rem created files in current directory (batch file directory).
:RunProgram
"C:\Path To Application\Application.exe" "%File1%" "%File2%"
rem Restore the initial current directory and also the initial environment
rem variables list on starting of this batch file as well as initial state
rem of command extensions and delayed environment variable expansion.
:EndBatch
popd
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 /? ... explains %~dp0 (drive and path of batch file) and %~nx0 (name and extension of batch file).
dir /?
echo /?
endlocal /?
for /?
goto /?
if /?
popd /?
pushd /?
rem /?
set /?
setlocal /?
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 with %ComSpec% /c and the specified command line appended.

How to create batch file that move files from sub-folder up one level renaming duplicates?

I already have a batch file that I can drop in any SHOW_NAME directory and it will move files from a sub-folder to its SEASON parent directory. For example:
F:\TV_SHOWS\SHOW_NAME\SEASON1\TITLE_EP1\title_episode1.mkv
F:\TV_SHOWS\SHOW_NAME\SEASON1\TITLE_EP2\title_episode2.mkv
F:\TV_SHOWS\SHOW_NAME\SEASON1\TITLE_EP3\title_episode3.mkv
F:\TV_SHOWS\SHOW_NAME\SEASON1\title_episode3.mkv
When it moves all files to the parent folder (SEASON1) the "title_episode3.mkv" is a duplicate and overwrites the original. How can I automatically rename by appending a number "title_episode3 (1).mkv"?
Here is the code that I use in a batch file:
#echo off
for /d /r %%f in (*) do (
for /d %%g in ("%%f\*") do (
for %%h in ("%%~g\*.mkv") do move "%%~h" "%%~f" >nul 2>&1
)
)
Thanks!
This commented batch file can be used for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Search for any file two directory levels below specified directory
rem and pass to subroutine MoveFile the name of the file with full path.
for /D %%A in ("F:\TV_SHOWS\SHOW_NAME\*") do (
for /D %%B in ("%%A\*") do (
for /F "delims=" %%I in ('dir "%%B\*" /A-D /B /S 2^>nul') do call :MoveFile "%%I"
)
)
endlocal
goto :EOF
:MoveFile
set "FilePath=%~dp1"
set "FileNameOnly=%~n1"
set "FileNameFull=%~1"
set "FileName+Ext=%~nx1"
set "FileExtension=%~x1"
rem For files staring with a dot and not containing one more dot.
if "%FileNameOnly%" == "" set "FileNameOnly=%~x1" & set "FileExtension="
rem Get path to parent folder ending with a backslash.
for /F "delims=" %%J in ("%FilePath:~0,-1%") do set "FileParent=%%~dpJ"
rem Uncomment the line below to see the values of the six File* variables.
rem set File & echo/
rem Does a file with current file name not exist in parent folder?
if not exist "%FileParent%%FileName+Ext%" (
rem Move the file to parent folder and if this was successful
rem delete the folder of the moved file if being empty now.
move "%FileNameFull%" "%FileParent%%FileName+Ext%" >nul
if not errorlevel 1 rd "%FilePath%" 2>nul
goto :EOF
)
set "FileNumber=1"
:NextFile
if exist "%FileParent%%FileNameOnly% (%FileNumber%)%FileExtension%" set /A "FileNumber+=1" & goto NextFile
move "%FileNameFull%" "%FileParent%%FileNameOnly% (%FileNumber%)%FileExtension%" >nul
if not errorlevel 1 rd "%FilePath%" 2>nul
goto :EOF
Running the batch file a second time on same directory with no new subdirectory and no new file does not change anything.
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 /?
for /?
goto /?
if /?
move /?
rd /?
rem /?
set /?
setlocal /?
See also:
the Microsoft article about Using Command Redirection Operators;
Single line with multiple commands using Windows batch file;
Where does GOTO :EOF return to?

Why does a batch file working before not work anymore as expected on some machines?

I have a batch script already working for some months. The purpose of the script is to create a folder based on the file name and rename the folder accordingly for a certain purpose. However, it stops moving the files to the created folder in the loop. I tested it on other machine and it was working fine, but on a particular machine; it is just not working.
What can I do to make the loop effective and why did the batch stop working (moving files to folder) after working for many months now?
setlocal EnableDelayedExpansion
for /F %%a in ('dir "C:\Program Files\WinSCP\Unconverted" /a-d /b') do (
if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a"
:func
set file=%~1
set dir=%file:~0,49%
mkdir "C:\Program Files\WinSCP\Unconverted\%dir%_fdc" 2>nul
rem ECHO "%file%"
rem ECHO "C:\Program Files\WinSCP\Unconverted\%dir%_fdc"
move /Y "C:\Program Files\WinSCP\Unconverted\%file%" "C:\Program Files\WinSCP\Unconverted\%dir%_fdc"
)
start "" "C:\Program Files\WinSCP\hide_conversion_window.exe"
I rewrote and commented the batch file as it contains several issues whereby most were not problematic as long as this batch file is stored in %ProgramFiles%\WinSCP\Unconverted and this directory is also the current directory on execution of the batch file as on double clicking the batch file.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFolder=%ProgramFiles%\WinSCP\Unconverted"
rem Process all files in source folder found by command DIR with ignoring
rem subfolders and listed in bare format which means only file names with
rem file extension but without file path. The batch file itself is skipped
rem if being also stored in the source folder specified above.
for /F "delims=" %%I in ('dir "%SourceFolder%\*" /A-D /B 2^>nul') do (
if /I not "%SourceFolder%\%%I"=="%~f0" call :MoveFile "%SourceFolder%\%%I"
)
rem Execute converter through AutoIt in a separate command process and
rem while conversion is running continue with batch processing which means
rem restoring previous environment and finally exiting batch file processing.
start "" "%ProgramFiles%\WinSCP\hide_conversion_window.exe"
endlocal
goto :EOF
rem MoveFile is a subroutine which expects to be called with one argument
rem being the name of the file to move with full file name which means
rem with file path, file name and file extension.
rem The first 49 characters of the file name define the name for target
rem folder on which "_fdc" must be appended for completion. This folder
rem is created without verification on success and then the file is
rem moved into this folder again without verification on success.
:MoveFile
set "FileName=%~nx1"
set "FolderName=%FileName:~0,49%_fdc"
mkdir "%~dp1\%FolderName%" 2>nul
move /Y "%~1" "%~dp1\%FolderName%\" >nul
goto :EOF
This batch file works for batch file being stored in a different folder than source folder or current directory is a different directory than the folder containing the batch file or a found file contains a space character or any other special character like &()[]{}^=;!'+,`~.
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 /?
for /?
goto /?
if /?
mkdir /?
move /?
set /?
setlocal /?
start /?
Read also the Microsoft article about Using Command Redirection Operators.
Thanks for the suggestion oldabi. Sometimes things do work and we are thinking is all perfect until it breaks down. Thanks for the suggestion. I just realised my mistake about missing bracket.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F %%a in ('dir "C:\Program Files\WinSCP\Unconverted" /a-d /b') do (
if not "%%~dpnxa"=="%~dpnx0" call :func "%%~a" )
goto conversion
:conversion
rem ::execute converter through autoit
start "" "C:\Program Files\WinSCP\hide_conversion_window.exe"
:func
set file=%~1
set dir=%file:~0,49%
mkdir "C:\Program Files\WinSCP\Unconverted\%dir%_fdc" 2>nul
rem ECHO "%file%"
rem ECHO "C:\Program Files\WinSCP\Unconverted\%dir%_fdc"
MOVE /Y "C:\Program Files\WinSCP\Unconverted\%file%" "C:\Program Files\WinSCP\Unconverted\%dir%_fdc"

Move video files from Pictures directory to Video directory

My photo import tool (Picasa) does a great job at importing photos and videos from my phone and camera. What I like is that it creates a subfolder under the Pictures directory based on the Photo Taken Date of each photo/video. So you end up with this structure:
C:\Pictures\2017-02-01\DSC_0001.jpg
C:\Pictures\2017-02-01\DSC_0002.jpg
C:\Pictures\2017-02-01\DSC_0003.mp4 <--- problem
The only problem is that it puts videos in this same structure under Pictures.
As such, I'd like to right a batch script to find and move all video files (.mp4, .avi, .mov) from the C:\Pictures directory to the C:\Videos directory, but also with the date subfolder....
i.e.
Move C:\Pictures\2017-02-01\DSC_0003.mp4 to C:\Videos\2017-02-01\DSC_0003.mp4
Note that the date subfolder may or may not exist under C:\Videos.
Also since these are large video files, and there are a lot of them, I'd prefer a process that actually does a move and not a copy then delete, for the sake of speed and disk space utilization as I am almost out of space (after re-organizing these files, I will be archiving off to a NAS).
Also prefer using RoboCopy, xcopy, or xxcopy as I have them and use them today on my machine. If massively easier using PowerShell scripting, I can learn that if it is easy to do.
Final Solution
I used Mofi's answer, but enhanced it just a bit to add a function to calculate the directory string length
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define folder with the pictures which is never deleted.
set "PicturesFolder=D:\Users\Chad\PicturesTest"
rem get string length of source directory to later use in a substring type function
call :strlen PicturesFolderDirectoryLength PicturesFolder
echo PicturesFolderDirectoryLength = %PicturesFolderDirectoryLength%
rem Change the current directory to directory with the pictures.
cd /D "%PicturesFolder%"
rem Search recursive in this directory for video files with
rem file extension AVI, MOV, MP4 or MPG and move those files.
for /F "delims=" %%I in ('dir /A-D /B /S *.avi *.mov *.mp4 *.mpg 2^>nul') do call :MoveVideo "%%I"
rem Discard all environment variables defined in this batch code
rem and restore initial current directory before exiting batch file.
endlocal
goto :EOF
rem MoveVideo is a subroutine called with name of current
rem video file name with full path by the FOR loop above.
rem It first defines target path for video file depending on source path
rem by removing the backslash at end and concatenating C:\Videos with the
rem source path omitting the first 11 characters which is C:\Pictures.
rem Then the target directory structure is created with redirecting the
rem error message output by command MD to handle STDERR in case of the
rem target directory already exists to device NUL to suppress it.
rem Next the video file is moved from source to target folder with silently
rem overwriting an already existing file with same name in target folder
rem because of using option /Y. Remove this option if a video file should
rem be kept in pictures folder and an error message should be displayed in
rem case of a video file with same name already existing in target folder.
rem Last the source folder is removed if it is completely empty which means
rem it does not contain any file or subfolder. All parent folders up to the
rem pictures folder are also removed if each parent folder is also empty
rem after deletion of an empty folder.
rem The subroutine is exited with goto :EOF and execution of batch file
rem continues in main FOR loop above with next found video file.
:MoveVideo
set "SourcePath=%~dp1"
set "SourcePath=%SourcePath:~0,-1%"
ECHO SourcePath=%SourcePath%
CALL SET "SourceSubFolder=%%SourcePath:~%PicturesFolderDirectoryLength%%%"
ECHO SourceSubFolder=%SourceSubFolder%
set "TargetPath=D:\Users\Chad\VideosTest%SourceSubFolder%"
echo TargetPath=%TargetPath%
md "%TargetPath%" 2>nul
move /Y "%~1" "%TargetPath%\%~nx1" >nul
:DeleteSourceFolder
rd "%SourcePath%" 2>nul
if errorlevel 1 goto :EOF
for /F "delims=" %%D in ("%SourcePath%") do set "SourcePath=%%~dpD"
set "SourcePath=%SourcePath:~0,-1%"
if /I not "%SourcePath%" == "%PicturesFolder%" goto DeleteSourceFolder
goto :EOF
:strlen <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
exit /b
)
Here is a commented batch code for this file moving task with keeping directory structure.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define folder with the pictures which is never deleted.
rem Note: ~11 in third line of subroutine MoveVideo must be
rem replaced by ~length of the folder path defined here.
set "PicturesFolder=C:\Pictures"
rem Change the current directory to directory with the pictures.
cd /D "%PicturesFolder%"
rem Search recursive in this directory for video files with
rem file extension AVI, MOV, MP4 or MPG and move those files.
for /F "delims=" %%I in ('dir /A-D /B /S *.avi *.mov *.mp4 *.mpg 2^>nul') do call :MoveVideo "%%I"
rem Discard all environment variables defined in this batch code
rem and restore initial current directory before exiting batch file.
endlocal
goto :EOF
rem MoveVideo is a subroutine called with name of current
rem video file name with full path by the FOR loop above.
rem It first defines target path for video file depending on source path
rem by removing the backslash at end and concatenating C:\Videos with the
rem source path omitting the first 11 characters which is C:\Pictures.
rem Then the target directory structure is created with redirecting the
rem error message output by command MD to handle STDERR in case of the
rem target directory already exists to device NUL to suppress it.
rem Next the video file is moved from source to target folder with silently
rem overwriting an already existing file with same name in target folder
rem because of using option /Y. Remove this option if a video file should
rem be kept in pictures folder and an error message should be displayed in
rem case of a video file with same name already existing in target folder.
rem Last the source folder is removed if it is completely empty which means
rem it does not contain any file or subfolder. All parent folders up to the
rem pictures folder are also removed if each parent folder is also empty
rem after deletion of an empty folder.
rem The subroutine is exited with goto :EOF and execution of batch file
rem continues in main FOR loop above with next found video file.
:MoveVideo
set "SourcePath=%~dp1"
set "SourcePath=%SourcePath:~0,-1%"
set "TargetPath=C:\Videos%SourcePath:~11%"
md "%TargetPath%" 2>nul
move /Y "%~1" "%TargetPath%\%~nx1" >nul
:DeleteSourceFolder
rd "%SourcePath%" 2>nul
if errorlevel 1 goto :EOF
for /F "delims=" %%D in ("%SourcePath%") do set "SourcePath=%%~dpD"
set "SourcePath=%SourcePath:~0,-1%"
if /I not "%SourcePath%" == "%PicturesFolder%" goto DeleteSourceFolder
goto :EOF
This batch file also removes all folders in C:\Pictures which become empty after moving the video files. But it does not remove folders which were already empty on starting 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.
cd /?
echo /?
endlocal /?
for /?
goto /?
if /?
md /?
move /?
rd /?
rem /?
set /?
setlocal /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of >nul and 2>nul. In the main FOR loop the redirection operator > is escaped with caret character ^ to be interpreted as literal character on parsing FOR command line and later as redirection operator on execution of DIR command line by FOR.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
XCOPY /T "%sourcedir%" "%destdir%"
FOR %%x IN (mp4 mov) DO (
FOR /f "tokens=1*delims=>" %%a IN (
'XCOPY /Y /s /d /F /L "%sourcedir%\*.%%x" "%destdir%"'
) DO IF "%%b" neq "" (
SET "topart=%%b"
SET "frompart=%%a"
ECHO(MOVE /y "!frompart:~0,-2!" "!topart:~1!"
)
)
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances.
The required MOVE commands are merely ECHOed 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)
The first xcopy creates the required subtrees, the second uses the /L option to list rather than copy the files
The loop on %%x assigns %%x to the required extensions. The output from the inner xcopy will be of the form fullsourcefilename -> fulldestinationfilename so it needs to be parsed using > as a delimiter, from-filename to %%a, to-filename to %%b. If %%b is not set, then this is the final line of xcopy's report (n files copied) which needs to be ignored. The to and from filenames need to be trimmed of unwanted, but fortunately constant character strings.
What is interesting is that there appears to be no way using xcopy to suppress prompting in the case where the destination filename already exists.

How to copy files into folders based on first 15 characters of file and folder name?

I want to copy more than 1000 files from a source folder like
sourcefolder\prod_de_7290022.xlsx
sourcefolder\prod_de_1652899.xlsx
sourcefolder\prod_de_6272899.xlsx
sourcefolder\prod_de_6189020.xlsx
sourcefolder\prod_de_7290022.wav
sourcefolder\prod_de_1652899.wav
sourcefolder\prod_de_6272899.wav
sourcefolder\prod_de_6189020.wav
sourcefolder\prod_de_7290022_mark.xlsx
sourcefolder\prod_de_1652899_mark.xlsx
sourcefolder\prod_de_6272899_mark.xlsx
sourcefolder\prod_de_6189020_mark.xlsx
to the right destination folder. The folder names are - based on another routine - long and only the first 15 characters are identical with the first 15 characters of each file name, like:
destination\prod_de_1652899_tool_big\
destination\prod_de_6272899_bike_red\
destination\prod_de_6189020_bike-green\
destination\prod_de_7290022_camera_good\
I am looking for a routine to copy the files into the folder, like sourcefolder\prod_de_1652899.xlsx into destination\prod_de_1652899_tool_big\.
Is here anyone with a good idea for a batch/script?
I suggest to use this commented batch code for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFolder=sourcefolder"
set "TargetFolder=destination"
rem Call subroutine CopyFile for each non hidden and
rem non system file found in specified source folder
rem and then exit processing of this batch file.
for %%I in ("%SourceFolder%\*") do call :CopyFile "%%~fI"
endlocal
goto :EOF
rem This is a subroutine called for each file in source folder.
rem It takes the first 15 characters from each file name passed
rem to this subroutine via first parameter and search for a
rem folder in target folder starting with same 15 characters.
rem If such a folder is found, the file is copied to this folder
rem and the subroutine is exited.
rem Otherwise a new folder is created for the file and if
rem this is indeed successful, the file is copied into the
rem newly created folder with an appropriate message.
:CopyFile
set "FileName=%~n1"
set "DirectoryName=%FileName:~0,15%"
for /D %%D in ("%TargetFolder%\%DirectoryName%*") do (
copy /B /Y %1 /B "%%~D\" >nul
goto :EOF
)
set "NewFolder=%TargetFolder%\%DirectoryName%_new"
md "%NewFolder%"
if exist "%NewFolder%\" (
echo Created new folder: %NewFolder%
copy /B /Y %1 /B "%NewFolder%\" >nul
goto :EOF
)
echo Failed to create folder: %NewFolder%
echo Could not copy file: %1
goto :EOF
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
call /?
copy /?
echo /?
endlocal /?
for /?
goto /?
if /?
md /?
rem /?
set /?
setlocal /?

Resources