/r/Batch

Photograph via //r/Batch

r/Batch is all about the Batch scripting language, which runs in the windows CMD language. It can be used within the CMD, or via .bat files.

Batch programming is the windows CMD language. It can be used within the CMD, or via .bat files.

Discord

Resources

SS64

DOS Tips

Windows Commands - 8.1/2008 and later

Batch Tutorials - YouTube Playlist

RULES

  1. Posts Must Relate to Batch: All Submissions should be related to Batch. Keep comments in a post on-topic.
  2. No Malicious Scripts: Do not distribute viruses or other harmful programs.
  3. Post all scripts in plaintext. If it will not fit in the box, put it in a pastebin.
  4. No Spam.
  5. Be Mature and Considerate: Help, don't hate. Always try to be supportive and help others learn.

/r/Batch

5,844 Subscribers

2

Minor tweak needed with script; please help.

Hello,

This script sits in a directory where a bunch of individual folders with video/srt files reside; it looks inside each folder and renames the files it finds to match the name of the folder where these files reside. It then goes back to the parent directory and does the same thing for any additional folders.

Problem: It works great most of the time. One issue I've come across with it is as follows:
Folder name: Dr. Giggles (1992)
It renamed the files in this folder as "Dr." and omitted the rest.
If anyone has any ideas how to fix it, I'd appreciate any feedback.

FOR /D /R %%# in (*) DO (
    PUSHD "%%#"
    FOR %%@ in ("*") DO (
        Echo Ren: ".\%%~n#\%%@" "%%~n#%%~x@"
        Ren "%%@" "%%~n#%%~x@"
    )
    POPD
)
7 Comments
2024/11/02
02:03 UTC

1

Batch file acting wierd

@echo off title create backup of currently open folder windows setlocal enabledelayedexpansion

powershell @^(^(New-Object -com shell.application^).Windows^(^)^).Document.Folder.Self.Path >> prevfolderpaths.txt

FOR /F "tokens=*" %%f IN (prevfolderpaths.txt) DO (

set "var=%%f" set "firstletters=!var:~0,2!"

IF "!firstletters!" == "::" ( ECHO start shell:%%~f >> foldersession.bat) ELSE ( ECHO start "" "%%~f" >> foldersession.bat)

)

del "prevfolderpaths.txt"

Ok, hear is the deal i am using the following as a backup for all open folder when windows crashes when i click on it it from explorer it works well, it creates a batch file like this that i can open after foldersession.bat

start "" "C:\Users\sscic\Downloads"
start "" "C:\Windows\symbolic links\New folder" start "" "C:\Users\sscic\Downloads"

Works well when i open it by clicking it, the problem is i tried to set it via task scheduler so I can back it every few minutes but doesnt work, it creates no foldersession I also tried launching it via explorer.exe C:\Users\sscic\explorer.exe "C:\Windows\symbolic links\New folder\foldersave.bat" to no avail its baffling me completely any pros here have an idea?

4 Comments
2024/10/29
08:17 UTC

1

Need help retrieving image files referencing a list in a .txt file

Solved in comments!!

I have a database txt file where the image names are listed without extension in parentheses, example:

<game name="amidar" index="" image=“"> <game name="anteater" index="" image="">

I’m looking for a script to find these files (they’re .pngs) searching a specific directory as well as its sub directories and copy them in a new destination folder. Can anyone help?

12 Comments
2024/10/28
19:52 UTC

1

Taskkill only working partially

Hi guys, some time ago i made a batch file to start all my game launchers to make it a bit easier (Ubi, Steam, Epic, EA and battle.net). Today ive decided that closing them all manually is a bit too annoying (since some dont allow you to fully close upon closing the window and continue running as a background process) so i went and created basically the opposite of the batch i use to open them by using

@ echo off

taskkill /IM UbisoftConnect.exe /F

taskkill /IM Steam.exe /F

taskkill /IM EpicGamesLauncher.exe /F

taskkill /IM EA.exe /F

taskkill /IM Battle.net.exe /F

exit

My problem now ist that it only works on Steam, Epic and battle.net, Ubi and EA stay open.

If anyone could tell me what im doing wrong id be very happy

(additionally id like to include bluestacks background process aswell but theres more than one and i dont know which is the right one)

8 Comments
2024/10/28
17:16 UTC

1

Help please

@echo off start /B color a lop: start /B /wait tree
goto lop

I would like this to be in f11 mode on startup how do I do that?

1 Comment
2024/10/28
16:31 UTC

1

Why is this firewall script not functioning as expected?

I'm trying to make a script that makes inbound rules that disable certain programs from getting traffic. I don't know how to test whether the rules are actually working or not. They are showing up in firewall but I don't know how I can verify that they work as intended. Nothing seems to change when using any of the programs. Please provide me some guidance.

netsh advfirewall firewall add rule name="Block msedge.exe" program="C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" protocol=tcp dir=in enable=yes action=block profile=any

netsh advfirewall firewall add rule name="Block Microsoft.Msn.Money.exe" program="C:\Program Files\WindowsApps\Microsoft.BingFinance_4.53.61371.0_x64__8wekyb3d8bbwe\Microsoft.Msn.Money.exe" protocol=tcp dir=in enable=yes action=block profile=any

netsh advfirewall firewall add rule name="Block Microsoft.Msn.News.exe" program="C:\Program Files\WindowsApps\Microsoft.BingNews_4.55.62231.0_x64__8wekyb3d8bbwe\Microsoft.Msn.News.exe" protocol=tcp dir=in enable=yes action=block profile=any

netsh advfirewall firewall add rule name="Block Microsoft.Msn.Weather.exe" program="C:\Program Files\WindowsApps\microsoft.bingweather_4.25.20211.0_x64__8wekyb3d8bbwe\Microsoft.Msn.Weather.exe" protocol=tcp dir=in enable=yes action=block profile=any

netsh advfirewall firewall add rule name="Block Microsoft.Photos.exe" program="C:\Program Files\WindowsApps\microsoft.windows.photos_2019.19071.12548.0_x64__8wekyb3d8bbwe\Microsoft.Photos.exe" protocol=tcp dir=in enable=yes action=block profile=any

netsh advfirewall firewall add rule name="Block XboxApp.exe" program="C:\Program Files\WindowsApps\microsoft.xboxapp_48.49.31001.0_x64__8wekyb3d8bbwe\XboxApp.exe" protocol=tcp dir=in enable=yes action=block profile=any

2 Comments
2024/10/27
23:40 UTC

1

set token for a not fixed position value FPS in a .txt

Hi, I need to find the FPS value in this txt file and set it to %ValueA% but the content will be different for different files, like resolution, codec or if the filename is displayed so the position of FPS changes

Thank you for any help :)

example A:

○ Video --vid=1 --vlang=ger 'blacksails-s02e01-1080p' (h264 1920x1080 25 fps) [default forced]

○ Audio --aid=1 --alang=ger (ac3 2ch 48000 Hz) [default forced]

example B:

○ Video --vid=1 --vlang=eng (h264 1920x1080 23.976 fps) [default]

○ Audio --aid=1 --alang=ger (dts 6ch 48000 Hz) [default]

○ Subs --sid=1 --slang=ger (ass) [default]

This was vegansgetsick approach, but after troubleshooting I found out that depending on the content the result is sometimes 1920x1080 because the filename was added and the position has changed.

rem Check Value.A.txt for "--vid=1" and retrieve the corresponding value in column %%g
for /f "tokens=1,2,3,4,5,6,7" %%a in (Value.A.txt) do (
    if "%%c" equ "--vid=1" set "ValueA=%%g"
)
3 Comments
2024/10/27
16:07 UTC

5

CSE version 1.2 will release on October 31th

Changes:

  1. Fix color scheme

  2. Word rap and other settings selection

  3. Other run cmd type

  4. ScanNow -- A debugger for malicious code

-- other changes will come soon

2 Comments
2024/10/26
20:42 UTC

1

My code skips one choice command and two echo commands say that echoing is off

This is the code (I will not translate anything that is in spanish):

rem at echo off, I don't put it normally because Reddit randomly breaks the code because of the @

set DLC=no

if not exist DLC mkdir DLC

title >nul
mode con: cols=37 lines=11

if exist DLC\Color_Plus.dat (
color b
)

:inicio

echo  ##################################
echo             Comprar DLCs
echo.
echo.
echo.
echo   (1) Color+.............($699.99)
echo   (2) World 10.............($6.99)
echo   (3) iMars Travel..($99999999.99)
echo.
echo  ##################################

choice /c 123 >nul

mode con: cols=37 lines=13

if errorlevel 3 goto iMars
if errorlevel 2 goto W10
if errorlevel 1 goto Color

:Color

if exist DLC\Color_Plus.dat (
color 4
echo Ya has comprado este DLC...
pause >nul
exit
)

echo  ##################################
echo             Comprar DLCs
echo.
echo   Color+ es la experiencia de
echo   juego definitiva! Agregale vida
echo   a Juego.bat!
echo.
echo   Precio: $699.99
echo   (S) Comprar
echo   (N) Cancelar
echo  ##################################

set DLC=Colors_Plus
choice /sn >nul

if errorlevel 2 cls
if errorlevel 1 goto compra

echo Has cancelado la compra...
pause >nul
goto inicio

:W10

if exist DLC\W10.dat (
color 4
echo Ya has comprado este DLC...
pause >nul
exit
)

echo  ##################################
echo             Comprar DLCs
echo.
echo   Expande la historia con el mundo
echo   10 y explora nuevas aventuras!
echo   
echo.
echo   Precio: $6.99
echo   (S) Comprar
echo   (N) Cancelar
echo  ##################################

set DLC=World 10
choice /sn >nul

if errorlevel 2 cls
if errorlevel 1 goto compra

echo Has cancelado la compra...
pause >nul
goto inicio

:iMars

if exist DLC\iMars.dat (
color 4
echo Ya has comprado este DLC...
pause >nul
exit
)

echo  ##################################
echo             Comprar DLCs
echo.
echo   iPlaceholder
echo   
echo   
echo.
echo   Precio: $99999999.99
echo   (S) Comprar
echo   (N) Cancelar
echo  ##################################

set DLC=iMars Travel
choice /sn >nul

if errorlevel 2 cls
if errorlevel 1 goto compra

echo Has cancelado la compra...
pause >nul
goto inicio

:compra

echo  ##################################
echo            Compra exitosa
echo.
echo   Has comprado %DLC%!
echo   Gracias por hacer la compra!
echo   Crear juegos es dificil...
echo.
echo   
echo    Espere a que se instale el DLC
echo   
echo  ##################################

pause >nul
exit
8 Comments
2024/10/26
19:31 UTC

3

How do i encode a batch file with base64?

So, i just made a batch file that basically opens a file when you put a certain password in, the only problem is that if you modify the file you can change the password so it ruins the whole point of the script. I want to know if it's possible to encode a batch file with base 64 so other people cant change the password without decoding it because they see only random numbers and letters. Also i want all the script to be encoded and not only the password (because it would've been really easy changing it). Down here is the code:

@echo off
Title File top secret

:start
echo.
echo Enter the password: 

set /p password=

if "%password%"=="123" (
    cls
    start Top_secret
    exit
) else (
    echo.
    echo Wrong password
    echo.
    pause
    exit
)
12 Comments
2024/10/26
12:17 UTC

3

compare 2 values from 2 txt files and make if/else decision

Hi, I need to compare 2 FPS values from 2 txt files and then act accordingly.

Value A is always there, value B can be missing. If B is present then it has to match with A, else=bad

If only A is present, or A matches B, then its good.

Value B "original frame rate" this line/entry can be completely missing, it depends on the file.

In summary: I have to filter out the missmatched once.

A=25 B=25 =good

A=25 B=x =good

A=25 B=23 =bad

Value A

Value B= Original frame rate, this line can be missing

Links to the txt files:

https://github.com/user-attachments/files/17528454/Value.A.txt

https://github.com/user-attachments/files/17528455/Value.B.txt

8 Comments
2024/10/26
00:42 UTC

1

Launch a program, then close the window

I made a batch file to change several settings at once when I switch to a different monitor setup. One of these is launching f.lux, one of those blue light filtering programs.

It launches f.lux correctly, including opening the window for the program. I want flux to just run in the background. Is there a way to close the window after f.lux launches with this batch file? Thanks!

5 Comments
2024/10/25
01:57 UTC

1

Taskbar drama: Pinning python script to taskbar without multiple icons (custom icon)

Hi everyone,

I'm trying to pin a Python script to my taskbar with a custom icon. I’ve tried the following approaches:

  1. Creating a shortcut for the batch file and pinning it.
  2. Using IExpress to create an EXE from the batch file, Python script, and an icon.
  3. Using PyInstaller to create an EXE from the Python script.

In all these scenarios, I’m able to pin the shortcut with my custom green clock icon, but when I click on it, a new window/icon with the default CMD icon appears in the taskbar. See screenshot with the two icons.

What I want is for the script to run and show the window (I don’t want it hidden), but I only want the green icon in the taskbar without a second one appearing.

Any ideas on how to make this work ?

Thanks for any suggestions!

2 Comments
2024/10/24
18:51 UTC

0

What should I cover in the next video? Drop your ideas⬇️- batchman

2 Comments
2024/10/23
14:47 UTC

6

Pushing VT100 Sequence to the full limit.

4 Comments
2024/10/22
20:06 UTC

1

Echoing simplified registry key names

Hello all,

I am using reg query to query registry key names.

I need to echo the simplified key names from HKEY_CLASSES_ROOT\Directory\shell

How do I output simply just the key names and set them to variables so that they can be deleted? This sounds overly complicated, I know. Here's an example

1. RegKeyExample1 (press number to delete)
2. RegKeyExample2

instead of echoing the whole spiel

"HKEY_CLASSES_ROOT\Directory\shell

(Default) REG_SZ none

HKEY_CLASSES_ROOT\Directory\shell\ex1 HKEY_CLASSES_ROOT\Directory\shell\ex2 HKEY_CLASSES_ROOT\Directory\shell\ex3 HKEY_CLASSES_ROOT\Directory\shell\ex4 HKEY_CLASSES_ROOT\Directory\shell\ex5 HKEY_CLASSES_ROOT\Directory\shell\ex6 HKEY_CLASSES_ROOT\Directory\shell\ex7 HKEY_CLASSES_ROOT\Directory\shell\ex8 HKEY_CLASSES_ROOT\Directory\shell\ex9 HKEY_CLASSES_ROOT\Directory\shell\ex10"

and when you press the corresponding number, it deletes. That's my end goal here.

Thanks y'all!!

2 Comments
2024/10/22
18:01 UTC

1

Reading from file that is already opened in another program

del Bestand.csv

For /F "tokens=1,2,3,4 delims=;" %%i in (Bestand_FUD.csv) do echo %%i;%%j;%%i-%%j;%%k;%%l >>Bestand.csv

I have this batch code which connects and add columns to a table and want it to be executable while "Bestand_FUD.csv" is already opened in Excel (for example).

Right now the cmd window will simply return "File not found" if the file is already. I'm a complete batch noob. Is there a way?

12 Comments
2024/10/22
12:17 UTC

2

Files Newer than 48 hours

I would have thought that this is easier, but apparently a single FORFILES cannot show all of the files that are newer than a certain number of days. The overall purpose is to monitor a directory of backup files and alert me if the backup has not run in the last several days.

After a long time scanning google for an example, I did come across the following:

rem Define minimum and maximum age in days here (0 means today):
set /A MINAGE=0, MAXAGE=2

set "MAXAGE=%MAXAGE:*-=%" & set "MINAGE=%MINAGE:*-=%" & set /A MAXINC=MAXAGE+1
> nul forfiles /D -%MINAGE% /C "cmd /C if @isdir==FALSE 2> nul forfiles /M @file /D -%MAXINC% || > con echo @fdate  @file"

This script works as I would like it to, but it merely prints out the names of the files that are 2 or less days old.
I have tried for a while (and failed) to convert it to a script that sets an environment variable of the number of files that are younger than a certain number of days. I tried using find /c and also tried to write this output to a file so I could count the rows. I'm not adept enough to do either.

The final piece would be to get this number and then write an if statement that prints an error if there are no files that meet the criteria. This would mean that the daily backup has not run for several days.

Any help with what I thought was a straightforward problem would be really appreciated!

4 Comments
2024/10/21
23:42 UTC

6

Discussing the del command!Learnt something new? Drop your thoughts!📩-batchman

1 Comment
2024/10/21
14:32 UTC

3

Moving all files from one directory to another with the same file names but different formats and different subfolders

Hi. As the tittle says, I am trying to move all the files from a folder without subfolders, to another directory with many subfolders that contains the files with exactly the same names but different formats

I went with ChatGPT and asked it for a script and it gave me this one:

 off
setlocal enabledelayedexpansion

:: Define the route of the folders
set carpetaA=D:\Samples (Category)\SFX\Rarefaction - A Poke In The Ear 1 (aif)
set carpetaB=D:\FIXED

:: Scan the subfolders of the folder A searchhing for files
for /r "!carpetaA!" %%f in (*) do (
    :: extract the name of the file without the extension
    set nombreArchivo=%%~nf
    set carpetaDestino=%%~dpf

    :: Search if exists a file with the same name (regardless of the extension)in the Folder B
    for %%g in ("!carpetaB!\!nombreArchivo!.*") do (
        if exist "%%g" (
            echo Copiando "%%g" a "!carpetaDestino!"
            move "%%g" "!carpetaDestino!"
        )
    )
)

echo Moving finalized.
pause

When I run the script it just says "Moving finalized. Press any key to continue...." but it really didn't move anything. I have been asking ChatGPT what could be wrong but all its suggestions haven't worked, so I was wondering if anybody around here could know why.

EDIT: I solved this using a Python code instead, you can see my comment below, so I would say this question was partially solved, since I never could make the .bat file to work.

EDIT 2: The real solution for the actual .bat fille was posted by a user below!

13 Comments
2024/10/19
08:17 UTC

2

Why does this batch script only work 90% of the time?

I asked chatGPT to create a Windows batch file to rename all the subdirectories of a certain directory sequentially from a starting number and incremented by 1 for each subdirectory. It worked just exactly like I wanted, except it left exactly 246 out of 2655 subdirectories untouched, and I can't for the life of me figure out why. None of the untouched subdirectories have any extraordinarily rare special characters in its name and many have no special characters at all. I have checked the subdirectory attributes and I am 100% certain none are marked Read-Only, Hidden or System.

I can manually rename the untouched subdirectories. If I rename it to something completely different than the original name, my renaming batch file will then rename it again, but if I just edit the subdirectory name (by adding some numbers to the front of the name) my renaming batch file still leaves it untouched.

This is the batch file chatGPT gave me:

@echo off
setlocal enabledelayedexpansion

set "base_path=C:\0"
set /a count=900001

rem Process subdirectories with full paths
for /f "delims=" %%D in ('dir "%base_path%" /b /ad') do (
    set "old_name=%%D"
    set "new_name=!count!"
    
    rem Echo for debugging purposes (can remove this later)
    echo Renaming "!old_name!" to "!new_name!"
    
    rem Attempt to rename using full path
    if exist "%base_path%\!old_name!" (
        ren "%base_path%\!old_name!" "!new_name!"
        if not errorlevel 1 (
            set /a count+=1
        ) else (
            echo Error renaming "!old_name!" to "!new_name!"
        )
    )
)

endlocal

I have tried this on both Windows 10 and Windows 11 machines, with exactly the same results.

What can I do to make this work on 100% of my subdirectories?
15 Comments
2024/10/18
23:26 UTC

3

Help with recursive batch script

I'm trying to create a bat file to check foldet and its recursive subfolders

ECHO OFF FOR /R %%G in (.) DO ( PUSHD %%G IF DIR /B /A:D is NUL (ECHO %%G "No Further directories here") POPD ) ECHO "Final directories verified!" PAUSE

Sadly this does not work for whatever reason.

6 Comments
2024/10/18
11:49 UTC

5

Hi, new to batch

Im learning the basics now but I don't REALLY know what batch is used for, I only see automating repetitive tasks. What else can batch be used for so I know what I'm getting into.

10 Comments
2024/10/15
23:40 UTC

2

curl finding URL for wrong object

I'm using the script below (which is just the first part of it) to search for the "zipball_url" from a github archive, but curl keeps finding the zipball for the oldest version (which is at the bottom of the page). I don't want curl to find the latest release, but instead find the latest available release (meaning it should also find the latest pre-release available if its the newest one available) and then download it. Is there anything I can do to stop it from downloading old releases and instead find the first "zipball_url" option at the top of the page?

@echo off
setlocal enabledelayedexpansion
set "scriptdir=%cd%"
pushd ..
set "parentdir=%cd%"
popd

cd %parentdir%



set "repo=https://api.github.com/repos/NegativeZero01/bss-quest-macro/releases"
set "macro_zipname=bss.zip"

set "grey="
set "red="
set "green="
set "yellow="
set "blue="
set "magenta="
set "cyan="
set "white="
set "reset="

call :get_path "curl" || exit /b
call :get_path "tar" || exit /b

echo ^<%yellow%Bss-quest-macro semi-automatic update-installation system%reset%^>
pause
echo ^<%green%Parent Directory found^^! Location: [%parentdir%]%reset%^>

for /F tokens^=4^ delims^=^" %%A in ('%_curl% -s "%repo%" ^| find "zipball_url"') do set "zip_url=%%~A"

if "%zip_url%"=="" (
    echo ^<%red%Failed to find .zip download URL%reset%^>
    echo ^<%magenta%- Try running%reset% %yellow%update.bat%reset% %magenta%again%reset%^>
    echo ^<%magenta%- If the issue persists, download the latest release manually%reset%^>
    <nul set /p "=%white%Press any key to exit . . .%reset%"
        pause >nul
    exit /b 1
)
echo ^<%green%Successfully found the .zip download URL: [%zip_url%]%reset%^>
echo:
echo %grey%Downloading . . .%reset%
echo:
%_curl% -sL "%zip_url%" -o "%macro_zipname%"
    if not exist "%macro_zipname%" (
    echo ^<%red%Failed to download the .zip file from%reset% %yellow%[%repo%]%reset%^>
    echo ^<%magenta%- Try again or install the latest release manually%reset%^>
    <nul set /p "=%white%Press any key to exit . . .%reset%"
        pause >nul
    exit /b 1
)
echo ^<%green%Successfully downloaded the%reset% %yellow%[%macro_zipname%]%reset% %yellow%.zip file%reset%^>
7 Comments
2024/10/13
19:34 UTC

1

How Can I Run 2 Apps Simultaneously and Close Them Both When One of the Two Exits?

Hello everyone,

As the title reads, I'd like to be able to open 2 programs at the same time and also have them close together when one of these 2 programs exits.

I've already figured out how to start them both but have no idea how I can achieve the last part.

Here's the code so far (I just added the game to the original batch file)

@echo off

set APACHE_SERVER_ROOT=%cd%\Apache24

start /min "" "%APACHE_SERVER_ROOT%\bin\httpd.exe"

start "" "%cd%\MHServerEmu\MHServerEmu.exe"

start "" "Z:\MHServerEmu-0.3.0\StartClientAutoLogin.bat"

exit

Any help would be greatly appreciated!

6 Comments
2024/10/12
05:40 UTC

1

Looking for a batch script for randomizing an image

The script would be intended to take a random PNG file present in G:\Main\Bkground_Source and place it in G:\Main\Bkground as Bkground.png, overwriting the current file. I've found occasional solutions online but doesn't seem to get the job done and I'm not quite good enough to troubleshoot why.

4 Comments
2024/10/10
15:01 UTC

2

How Can I Create a Batch Script That Changes ASCII Character Colors with a Gradient and Jumps to a Label on Enter?

I'm new to Batch scripting, and I want to create a program where an ASCII character changes color (with a gradient). When you press Enter (using pause > nul, if I'm not mistaken), it should jump to a specific label.

2 Comments
2024/10/10
06:29 UTC

2

Using Variables in a command not working????

:WiFinding
netsh wlan show profile
set /p "WifiName = Wifi Name? *CASE SENSITIVE:"
netsh wlan show profile %WifiName% 
netsh wlan show profile name = %WifiName% key=clear
pause
echo Scan Completed? Exit?
pause
exit

on of my Wifi's is named "Redmi". When i type it in as the wifi name , it gives me an error with " profile key=clear was not found". the program then continues as usual.

2 Comments
2024/10/09
15:17 UTC

Back To Top