Showing posts with label Batch Scripting. Show all posts
Showing posts with label Batch Scripting. Show all posts

Sunday, May 31, 2026

Batch Program - Move files of specific type to Target folder using BAT file

Using the following Batch programming code, you can Move files of specific type to a target folder. 
  • SET command is used to declare variable and initialize it.
  • If Target folder is missing then MD command creates the target folder.
  • CD command is is used to change directory from D Drive to G:\PowerPoint Y25 folder.
  • The FOR loop loops all MP4 files in the source folder and 
  • DO command uses a number of actions inside its parentheses ().
  • %%i is loop variable which scope is inside the loop.
  • %%nxi stands for filename with extension for each i i.e. mp4 type file.
  • MOVE command is used to move from source to target folder.
  • REM stands for comments in batch code.
  • ECHO command prints the text on console.
@ECHO OFF

SET "SourceDir=G:\PowerPoint Y25"
SET "DestinationDir=G:\Lesson4"
SET "SearchTerm=React"

REM --- 1. Ensure the destination directory exists ---
IF NOT EXIST "%DestinationDir%\" MD "%DestinationDir%"

REM --- 2. Change to the source directory for the search ---
CD /D "%SourceDir%"

REM --- 3. Loop through all PDF files and check the filename ---
FOR %%i IN (*.mp4) DO (
    ECHO Checking: "%%~nxi"
    
    REM Note: Removed the /I switch for case-sensitivity
    ECHO "%%~nxi" | FIND "%SearchTerm%" >NUL
    
    REM This checks: IF the error level is NOT greater than or equal to 1
    REM i.e., IF error level is exactly 0 (Match Found)
    IF NOT ERRORLEVEL 1 (
        ECHO **MATCH FOUND! Moving file: "%%~nxi"**
        
        REM Move the file to the destination folder
        MOVE "%%i" "%DestinationDir%"
    ) ELSE (
        ECHO No match found.
    )
)

PAUSE

Saturday, May 30, 2026

Batch Program - Create Multiple files using BAT command

You can Create 1oo Text files with file extension js, each filename begins with exercise word followed by a nuber, using following BAT command:
@echo off
    FOR /L %%i IN (1,1,99) DO (
        echo This is loop iteration %%i
         type nul > exercise%%i.js
    )
    pause
The following BAT command creates a blank text file named exercise.txt:
@echo off
type nul > exercise.txt

Thursday, November 6, 2025

Batch Program - String Manipulation in Batch Scripting

Look at the following batch script in Example1 to understand the String Manipulation in Batch Scripting. The set statement is used to declare and initialize the variable named filename. In each ECHO statement, the variable filename is manipulated. The colon symbol implies that the command line interpreter expands the variable till it reaches the colon. Now at compile time, string is expanded and it becomes document.pdf. Now the string manipulation operation begins after tilde(~) symbol. This tilde sign implies that it will start working on the string "document.pdf". The minus(-) sign is followed by a number e.g. 1,2,3,4 etc. This implies that 1,2,3,4 number of characters will be removed from the end of the string and returned. Look at the output for better comprehension.

EXAMPLE1. Remove Characters from the End of string


@echo off
set "filename=document.pdf"
echo "%filename:~-1%" :: Last 1 character
echo "%filename:~-2%" :: Last 2 character
echo "%filename:~-3%" :: Last 3 character
echo "%filename:~-4%" :: Last 4 character
echo "%filename:~-6%"
pause

OUTPUT

"f" :: Last 1 character
"df" :: Last 2 character
"pdf" :: Last 3 character
".pdf" :: Last 4 character
"nt.pdf"
Press any key to continue . . .

EXAMPLE2. Remove Characters from the Start of string

In example1, we saw how to remove characters from the end of string. Now we see how to remove characters from the start position of string. Already we have seen that string manipulation begins with ~ sign. If tilde is followed by a number such as 1 or 2 etc then that number of characters from removed from the starting posiotn of string. Look at the output for better comprehension.

@echo off
set "filename=document.pdf"
echo "%filename:~1%" :: First 1 character
echo "%filename:~2%" :: First 2 characters
echo "%filename:~3%" :: First 3 characters
echo "%filename:~4%" :: First 4 characters
@pause

OUTPUT

"ocument.pdf" :: First 1 character
"cument.pdf" :: First 2 characters
"ument.pdf" :: First 3 characters
"ment.pdf" :: First 4 characters
Press any key to continue . . .

EXAMPLE3. Add Characters in the beginning of string

Prefixing Text to string in batch scripting is very easy. You need no special operator for this. Look at the following example to prefix each subfolder in a folder:

Prefix Folders in a Directory or Drive

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

REM Create 5 folders
SET "folder_name=Folder"
SET "count=5"
FOR /L %%c in (1,1,5) DO (
    MKDIR "%folder_name%_%%c"
)

REM Prefix Each Folder Name
SET "folder_prefix=Batch_Program_"
FOR /D %%x in ("%folder_name%*") DO (
    SET "original=%%x"
    REM The REN command is to change the folders name.
    REM We use !original! here to get the value set in the same block.
    REN "!original!" "%folder_prefix%!!original!"
    ECHO Renamed: "!original!" to "%folder_prefix%!!original!"
)

ENDLOCAL
pause

REMARK: You must have clarity about string expansion at compile time and at run time. The string variable sandwiched between % e.g. %text_string_variable% is expanded at compile time but !text_string_variable! is expanded at runtime. Since variable original is declared at runtime when the FOR loop is executing, so the expansion of original variable need runtime variable expandor i.e. exclamation sign. The value of variable original is decided by %%x which value is decided at runtime.


EXAMPLE4. Get Substring of a String

Look at the following example to see how substring from a string is derived. The full explanation of string manipulation is given ahead together with another example.

@echo off
REM Set blue background and light yellow foreground color
color 1E
:: The variable must be immediately followed by = sign to initialize
set myname=AjeetKumar2023

:: returns AjeetKumar2023
echo %myname%

:: returns Ajeet The start offset is 0 and length offset is 5
:: length offset tells how many characters to grab
echo %myname:~0,5%

:: returns Kumar2023, skip first 5 chars and peek next all chars
:: start offset is 5 and length offset is not given
:: So, it will grab all characters from start offset position
echo %myname:~5%

:: returns mar20, skip first 7 characters and grab next 5 characters 
echo %myname:~7,5%

:: returns ma, skip first 7 characters and grab next 2 chars
echo %myname:~7,2%

:: returns Kumar
:: It skips first 5 characters and 
:: length offset from end is 4. What does it mean?
:: It means that grabbing direction will still be from start position
:: but length offset tells the position where the grabbing will stop.
echo %myname:~5,-4%

pause
@echo on

EXAMPLE5. Get String from in Between of a string

Now we see how to remove first 3 characters from the start and 4 characters from the end and then return the remaining string?

The core command to achieve this uses the syntax:

%variable:~start,length%

The tilde symbol tells about string manipulation operation.
The start is a number which can be positive or negative. Already we have seen 2 examples in this regard. We have not seen the second parameter which is length.
The basic idea is to manipulate a string variable, we use colon(:) after the variable to denote that the variable expansion is done now. The tilde denotes to start string variable manipulation. If start is postive number then skip that number of characters of the string variable from the beginning. Similarly, if start is negative number then skip that number of characters of the string variable from the end. This much we have already seen.

Now, we look at length parameter. The length can be positive or negative as well.

Step 1: Removing the First 3 Characters (from the Start)
To remove the first 3 characters, you start counting the position from the 4th character (which is index 3 in programming terms, but the offset is simply 3 in batch).

Syntax: !OriginalString:~3!

This takes the string starting at the 3rd character offset (i.e., the 4th character) and goes to the end.

Step 2: Removing the Last 4 Characters (from the End)
Next, to remove the last 4 characters from the result of Step 1, you use a negative number for the length parameter.

Syntax: !StringFromStep1:~0,-4!

~0 means start at the beginning of StringFromStep1.

,-4 means stop 4 characters before the end of StringFromStep1.

Complete Example
Now we look at the complete, working Batch script example. We need to enable Delayed Expansion (setlocal enabledelayedexpansion) to handle the intermediate variable assignment correctly within a block of code.

@echo off
setlocal enabledelayedexpansion

:: 1. Define the original string
set "OriginalString=ABCDEFGHIJKLMNO"
:: Length of OriginalString is 15
:: Characters to keep: D-E-F-G-H-I-J-K
:: Expected Result: DEFGH IJK

echo Original String: **%OriginalString%**
echo.

:: 2. Remove the first 3 characters (A, B, C)
set "TempString=!OriginalString:~3!"
echo After removing first 3 chars (ABC): !TempString!
:: TempString is now: DEFGHIJKLMNO

:: 3. Remove the last 4 characters (L, M, N, O) from the TempString
set "FinalString=!TempString:~0,-4!"
echo After removing last 4 chars (LMNO): **!FinalString!**
echo.

endlocal
pause

OUTPUT
Original String: ABCDEFGHIJKLMNO

After removing first 3 chars (ABC): DEFGHIJKLMNO
After removing last 4 chars (LMNO): DEFGH IJK
This method is the most efficient and standard way to perform this kind of string slicing in Batch scripting.

Batch Program - The SET statement in Batch Script and Loop Variable

Some Facts:

  • The set statement is used to declare and initialize a variable.
  • The variable initialization inside quote is considered best practice.
  • The replaceable parameter is prefixed with % on command line window or %% in batch file. 
  • Note that % is not both side of replaceable parameter as we do with variables declared with set statement.
  • The replaceable parameters are part of loop implicit varibles.
  • The SET statement is used to declare and initialize variable explicitly.
  • The loop variable is implicitly declared.
  • The SET variable can be of more than one letter but loop variable must be of single letter.

@echo off

set x=1222
set "y=234"
set "z=ajeet"
set "myVariable=Ram Krishna"

echo %x% %y% %z% %myVariable%

REM FOR /L implies for loop for a set of numbers
REM (1,3,44) implies (start,step,end) i.e. number between 1 and 44 and step value is 3
FOR /l %%n in (1,3,44) DO (echo %%n)

pause

Batch Program - GOTO Statement in Batch Scripting for infinite loop

The built-in %RANDOM% environment variable and GOTO statement can be used for infinite loop.

@echo off
mode 400
color 03

:label
echo %random% %random% %random% %random% %random% %random% %random% %random% %random% %random% %random% %random%
goto label

pause


Type GOTO/? in CMD window for more information as I have done:

C:\Users\ajeet> GOTO/?

Directs cmd.exe to a labeled line in a batch program.

GOTO label

The label specifies a text string used in the batch program as a label.  You type a label on a line by itself, beginning with a colon.  If Command Extensions are enabled GOTO changes as follows:  GOTO command now accepts a target label of :EOF which transfers control to the end of the current batch script file.  This is an easy way to exit a batch script file without defining a label.  Type CALL /?  for a description of extensions to the CALL command that make this feature useful.


Randomly Set CMD Window Background Color

Before setting the console background color randomly, do the following to see the concepts behind this. 
Open CMD window and Run the following command: 

>COLOR 2E

It will set windows background color Green and foreground Light Yellow.

>COLOR/?

It will show you the helpful information about COLOR command. This command sets the default console foreground and background colors. 

COLOR [attr]    

The attr specifies color attribute of console output. Color attributes are specified by TWO hex digits - the first corresponds to the background; the second the foreground. Each digit can be any of the following values:

Color Code

0 = Black

  8 = Gray

1 = Blue

9 = Light Blue

2 = Green

  A = Light Green

3 = Aqua

B = Light Aqua

4 = Red

C = Light Red

5 = Purple

 D = Light Purple

6 = Yellow

 E = Light Yellow

Example: COLOR 2E will set background Green and foreground Light Yellow.

Note: You can use A, B, C, D and E hex digit in upper or lowercase.

If no argument is given, this command restores the color to what it was when CMD.EXE started.  This value either comes from the current console window, the /T command line switch or from the DefaultColor registry value. 

The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute the COLOR command with a foreground and background color that are the same.  Example: "COLOR fc" produces light red on bright white

Example
We can use the built-in %RANDOM% environment variable and the modulo operator (%%) to generate random numbers between 0 and 9 and then colorize the windows randomly. The following script randomly colorize background color while foreground color is light yellow color(E)

@echo off
REM Generate a random number between 0 and 9
set /a RANDOM_DIGIT=%RANDOM% %% 10

echo The random number (0-9) is: %RANDOM_DIGIT%
COLOR %RANDOM_DIGIT%E

pause

Batch Program - Different File Modifiers in Windows Batch Scripting

File Modifiers are used with replacement parameter in FOR loop. They begin with ~ tilde sign which is followed by replacement parameter(also called loop variable) which can be of 1 letter.

You can run following examples individually to learn about file modifiers.

SYNTAX: %%Tilde Then Single Letter File Modifier Then Single Letter Loop Variable
Note that you can combine file modifiers also.

Example

@echo off

REM List filename of each batch file, file modifier is not used here

FOR %%f in (*.bat) DO echo %%f

pause

Example

@echo off

REM List filename without extension of each batch file, ~n for filename

FOR %%f in (*.bat) DO echo %%~nf

pause

Example

@echo off

REM List file extension of each file, ~x for file extension

FOR %%f in (*) DO echo %%~xf

pause

Example

@echo off

REM List file name with extension of each file, ~nx for file name and extension

FOR %%f in (*.bat) DO echo %%~nxf

pause

Example

@echo off

REM List full path of each file, ~f for fully qualified path including filename

FOR %%f in (*.bat) DO echo %%~ff

pause

Example

@echo off

REM List full path of each file, ~f for fully qualified path excluding filename

FOR %%f in (*.bat) DO echo %%~pf

pause

Example: This example shows the usage in one script.

@echo off
SET "tab= "

ECHO Get list of files 
for %%i in (*) do (
 echo %tab% %%i
)


ECHO Get list of files with fullpath
for %%i in (*) do (
 echo %tab% %%~fi
)

ECHO Get list of files with name only
@echo off
for %%i in (*) do (
 echo %tab% %%~ni
)

ECHO Get list of files with extension only
@echo off
for %%i in (*) do (
 echo %tab% %%~xi
)

ECHO Get list of files with name and extension only
@echo off
for %%i in (*) do (
 echo %tab% %%~nxi
)

ECHO Get list of files with path
@echo off
for %%i in (*) do (
 echo %tab% %%~pi
)


The output of this script is as follows:
Get list of files
         file.txt
         file2.txt
         file_info.bat
Get list of files with fullpath
         D:\BAT Examples\New folder\file.txt
         D:\BAT Examples\New folder\file2.txt
         D:\BAT Examples\New folder\file_info.bat
Get list of files with name only
         file
         file2
         file_info
Get list of files with extension only
         .txt
         .txt
         .bat
Get list of files with name and extension only
         file.txt
         file2.txt
         file_info.bat
Get list of files with path
         \BAT Examples\New folder\
         \BAT Examples\New folder\
         \BAT Examples\New folder\
Press any key to continue . . .

Tips: To get the complete list of file modifier, run the command FOR/?

Here is some list:

    %~I         

 expands %I removing any surrounding quotes (")

    %~fI        

 expands %I to a fully qualified path name

    %~dI       

 expands %I to a drive letter only

    %~pI       

 expands %I to a path only

    %~nI       

 expands %I to a file name only

    %~xI       

 expands %I to a file extension only

    %~sI        

 expanded path contains short names only

    %~aI       

 expands %I to file attributes of file

    %~tI        

 expands %I to date/time of file

    %~zI       

 expands %I to size of file



Batch Program - Positional Arguments in Windows Batch Scripting

We can run a batch file either of the following ways:
  1. By mouse click of the batch file
  2. By running the batch file on CMD prompt.
In the second case, we can easily pass arguments to the command.

Look at the following Batch Script file args.bat:

@echo off
echo First argument is %1
echo 2nd argument is %2
echo 3rd argument is %3
pause

We can pass three arguments when running the batch script file. Look at the image below:

Now run the following command in CMD window: SHIFT/? We get the following help:
C:\Users\ajeet>shift/?
Changes the position of replaceable parameters in a batch file.

SHIFT [/n]

If Command Extensions are enabled the SHIFT command supports the /n switch which tells the command to start shifting at the nth argument, where n may be between zero and eight.  For example: SHIFT /2 would shift %3 to %2, %4 to %3, etc. and leave %0 and %1 unaffected.

The SHIFT command is used shift the arguments. The SHIFT command moves the arguments down, essentially discarding the first one (%1) and moving the second one (%2) into the %1 position, the third (%3) into %2, and so on. This is extremely useful for looping through an unknown number of arguments. Look at the following example file args2.bat in this regard:

@echo off
echo First argument is %1
shift
echo 2nd argument is %1
shift
echo 3rd argument is %1
pause

Look at the result when we run the bat file with arguments:



Batch Program - Get Input From User In Windows Batch Scripting and Do Arithmetic

In the post, we will see how to get input from user in windows batch scripting and do arithmetic operation.
The SET statement provides /P switch which is used to get input on prompt.

Look at the following script to see how user is prompted to input two numbers.
The sum result is displayed thereafter.

@echo off
SET /P x=Enter value of x: 
SET /P y=Enter value of y: 
set /A z=%x%+%y%
echo The sum of x=%x% and y=%y% is %z%
pause

Tips:

  • Give extra space after colon(:)
  • The /A switch is used to write arithmetic expression. When /A is followed by expression then that expression is evaluated as arithmetic operation. Look at the following script in this regard:

@echo off


set i=1
for %%f in (*) do (
@echo %i% %%~nf
set /a i+=1
)
endlocal
@pause

NOTE:
  1. The += is a compound operator used in  i+=1 which is an arithmetic expression. Since variable is reinitialized in each iteration, simple SET statement will not be enough. We use /A switch to imply that i+=1 is an arithmetic expression.
  2. Here, wildcard (*) and (*.*) have subtle difference. The *.* implies to loop through all files and folders which contain a period symbol in their names. But * is just any file or folder.


Batch Program - Prefix all subfolders in a folder using Windows Batch Scripting

The following batch script shows how to prefixes all folders with "Java_".

@echo off
set "prefix=Java_"

REM The /D switch iterates over directory names only.
REM The * wildcard matches all folders.
FOR /D %%i in (*) DO (
    echo "%prefix%%%i"
)

@pause

To really prefix all subfolders of the folder, use REN instead of ECHO command with following minor change:

@echo off
set "prefix=Java_"

REM The /D switch iterates over directory names only.
REM The * wildcard matches all folders.
FOR /D %%i in (*) DO (
    REN "%%i " "%prefix%%%i"
)

@pause

Tips

  • REN command is used to rename file or folder. For more details run the command REN/?

Batch Program - Create Any Number of Folders using Windows Batch Scripting

Run the following code to create 5 folders:


My folder1

My folder2

My folder3

My folder4

My folder5



@echo off

set "foldername=My folder"

set "count=5"


REM Replacement parameter is prefixed with %% in script file

REM The set variables are expanded using % symbol sandwitching them



FOR /L %%i in (1,1,%count%) DO (

MKDIR "%foldername%%%i"


)

pause


Tips

  • You can test the script using ECHO in place of MKDIR. This will show the result in the window.
  • You can change the foldername and count as per the need.
  • To List only folders, use the following switch

D:\BAT Examples\>dir/b/A:D
My folder1
My folder2
My folder3
My folder4
My folder5 










Wednesday, November 5, 2025

Batch Program - Conditionally Remove Prefix from each file using Windows Batch Scripting

The following script removes prefix "New book " from each file. Only those files are processed which have "New book " as leading text.


@echo off

set "prefix=New book "

set "prefix_length=9"

for %%i in ("%prefix%*.txt") do (

set "filename=%%i"

setlocal enabledelayedexpansion

ren "!filename!" "!filename:~%prefix_length%!"

endlocal

)

@pause


Script Explained

  • The script loops through all text files which have prefix New book with single trailing space. The total count of this prefix is 9.
  • Use FOR loop to loop though all such files.
  • Store filename in a temporary variable named filename.
  • Note that %%i represents replacable parameter of FOR loop.
  • At compile time all the commands used inside () are expanded. In other words, strings are expanded by replacing the varibles by their values. For example, "%prefix%*.txt" is replaced as "New book *.txt". Note that * is dynalically replaced by some filename during iteration. Same happens with ren command. It is expanded as ren "!filename!" "!filename:~9!" 
  • At runtime, the filename variable is replaced by current filename in each iteration of loop. The exclamation sign represents the string expansion at runtime while percent sign represents the string expansion at compile time. Note that expansion of variable happens that is sandwitched between exclamation sign or percent sign. The %% sign is replacable parameter of FOR loop variable. It is not for expansion of set variables.

Tips

  • Before running the script, replace ren by echo. It will help you to see the final output on screen without actual result. You can test by the following script:

@echo off

set "prefix=New book "

set "prefix_length=9"

for %%i in ("%prefix%*.txt") do (

set "filename=%%i"

setlocal enabledelayedexpansion

echo "!filename!" "!filename:~%prefix_length%!"

endlocal

)

@pause

Sunday, July 6, 2025

Batch Program - BAT file to extract all zipped files from a source folder to target folder

In a folder there are many zipped files at Source Path = C:\Users\ajeet\Desktop\Sources_zips. If you want to extract all zip files in one go then you can use BAT file.
@echo off
setlocal

set "ZIPFOLDER=C:\Users\ajeet\Desktop\Sources_zips"
set "DESTFOLDER=%ZIPFOLDER%\Extracted"

if not exist "%DESTFOLDER%" (
    mkdir "%DESTFOLDER%"
)

for %%I in ("%ZIPFOLDER%\*.zip") do (
    "C:\Program Files\7-Zip\7z.exe" x "%%I" -o"%DESTFOLDER%\%%~nI" -y
)

echo All files extracted.
pause



Hot Topics