Batch Scripts

Batch File Builder

Make a Windows .bat script by snapping blocks together. Every block says what it does in plain English and shows the exact line of code it adds, so you can see how batch works as you build.

Windows only. Blocks that change system settings say "Needs Run as administrator" when you press their ?. Read through a script before running it, and keep backups before deleting things.

Keeps this tool on this device so it works without internet, even after a refresh.

Had fun, or did this help? I’d appreciate any donation :) Not needed, but money buys temporary happiness at least lol

How to use Batch File Builder

  1. Find a block. Each one says what it does in plain English and shows the line of code it adds. Search works too, like "delete", "ping" or "wait". They're along the bottom of the tool; on a phone, tap Blocks to open them.
  2. Drag it into your script, or tap it to add it. Tap a block in your script first and new blocks go right after it. Tap the "then" or "do this" strip of an if or loop block and they go inside it.
  3. Fill in the boxes. The code under each block and the whole file update as you type, and each block's name sits above its lines in the code so you can see which part does what.
  4. Press Download .bat, then double-click the file to run it. Your blocks stay saved in this browser, so you can come back and change them.

Move blocks by dragging their ⠿ handle, or tap a block and use its arrows. Dragging a block back onto the list deletes it. Ctrl+Z undoes and Ctrl+Y redoes. With a block highlighted, Delete removes it, Ctrl+D copies it, Alt+↑ and Alt+↓ move it, and Esc lets go. The ▾ on an if, loop or other block that holds blocks folds it to one line, so long scripts are easier to get around; the code doesn't change. If a block would break the script, like a label inside a loop or a variable that won't update inside an if, it shows a warning that says how to fix it.

Click into a box and a list of variables pops up under it: the ones your script sets, the loop's own variable when you're inside a loop, and handy Windows ones like %USERPROFILE% and %DATE%. Tap one to drop it in where the cursor is, so there's no typo to hunt down later.

Want to skip a block for now without losing it? The ⊘ button turns it off. It stays in your script, greyed out, and its code becomes a rem line that doesn't run. Press it again to turn it back on.

Blocks that delete or wipe things, like deleting a folder with everything in it, mirroring a folder, deleting registry settings or shutting down, get a red edge. Tick ask Y/N first on one and the script stops to ask before it runs that step.

Need web pages, spreadsheets or images? Those are easier in Python, and the Python Script Builder works the same way, pip packages included.

Already have a .bat file? Paste a .bat turns its simple lines into blocks and keeps everything else exactly as it was in "Any command" blocks.

Every block and what it does

All 148 ready-made blocks, with the code each one makes using its starting values. Open a group to see them.

Basics 16
BlockCodeWhat it does
Hide the commands@echo offStops cmd printing every command before it runs it, so only your own messages show. Almost every script starts with this.
Show a messageecho Hello!Prints a line of text in the window. Special characters like & | < > are escaped for you, and %VARIABLES% still get filled in.
Empty lineecho.Prints an empty line, handy for spacing out messages.
Note to yourselfrem What this part doesA comment. cmd skips it completely, it is just there to explain the script to whoever reads it.
Window titletitle My scriptSets the text in the title bar of the script window.
Wait for a keypauseWaits until a key is pressed. Without it, a script that was double-clicked closes the moment it ends, before you can read anything.
Clear the windowclsWipes everything printed so far.
Window colorscolor 0AChanges the text and background color of the whole window.
Wait some secondstimeout /t 5 >nulPauses for a number of seconds. -1 waits until a key is pressed. Tick "no skipping" so a key press can't cut it short.
Stop the scriptexit /b 0Ends the script. The code tells whatever started it how it went: 0 means fine, anything else means something failed. "Close the window too" also closes the cmd window.
Use UTF-8 textchcp 65001 >nulSwitches the window to UTF-8 so accented letters, emoji and other languages show properly.
Keep variables localsetlocalVariables you set after this disappear when the script ends instead of leaking into the window. "Delayed expansion" lets you use !VAR! to read a variable that changes inside a loop or if block.
End local variablesendlocalEnds a setlocal early, throwing away the variables set since then.
Window sizemode con: cols=100 lines=30Resizes the script window, counted in characters and lines.
Popup message boxpowershell -NoProfile -Command "Add-Type -AssemblyName PresentationFramework; [System.Windows.MessageBox]::Show('Time to take a break', 'Reminder') | Out-Null"Shows a normal Windows message box with an OK button, using PowerShell.
Beeppowershell -NoProfile -Command "[console]::beep(880,300)"Plays a short beep.
Variables & input 13
BlockCodeWhat it does
Set a variableset "FOLDER=%USERPROFILE%\Documents"Saves some text under a name. Use it later as %name%. The quotes around the whole thing keep stray spaces out.
Do mathset /a "COUNT=COUNT+1"Works out a sum with whole numbers: + - * / and % (remainder, written %% in a script). Variables can be used without % signs, like count+1.
Ask the user to type somethingset /p "ANSWER=Your name: "Shows a question and waits for the person to type an answer and press Enter. The answer goes in the variable.
Ask a multiple choice questionchoice /c YN /m "Continue"Waits for one key press from a list. Set the seconds to 0 to wait forever. The answer comes back as a number: the first key is 1, the second 2 and so on. Check it with an "If the last command's result" block.
Ask yes or nochoice /m "Delete these files"
if errorlevel 2 exit /b
A ready-made yes/no question: if they press N the script stops.
Use the file dropped on the scriptset "FILE=%~1"When files are dragged onto a .bat (or it is run with extra words after it) they arrive as %1, %2… This copies one into a variable with its quotes removed.
Next dropped itemshiftMoves %2 into %1, %3 into %2 and so on, to go through many dropped files one at a time.
Today's date into a variablefor /f "delims=" %%I in ('powershell -NoProfile -Command "Get-Date -Format yyyy-MM-dd"') do set "STAMP=%%I"Puts the current date and time in a variable in a fixed format, so it works the same on every PC whatever its language. Great for file and folder names.
First line of a file into a variableset /p "LINE=" < "settings.txt"Reads the first line of a text file into a variable.
Command output into a variablefor /f "delims=" %%I in ('hostname') do set "HOST=%%I"Runs a command and saves what it prints (the last line if there are several). Write | as ^| inside the command.
Save a variable for goodsetx MY_TOOL_HOME "C:\Tools"Saves a variable into Windows so new windows and programs see it too (not the window that ran it). Tick "for every user" to set it machine-wide, which needs Run as administrator.
Delete a variableset "ANSWER="Empties a variable so "if defined" sees it as not set.
Random numberset /a "ROLL=%RANDOM% %% 6 + 1"Picks a random whole number from 1 up to the number you give.
If & jump 15
BlockCodeWhat it does
If a file or folder existsif exist "%USERPROFILE%\Desktop\notes.txt" (
…
) else (
…
)
Runs the blocks inside only if the path is there (or isn't). End a folder path with \ to check it is a folder and not a file.
If two things matchif /i "%ANSWER%"=="yes" (
…
) else (
…
)
Compares two pieces of text or two numbers, usually a variable with something. "is" compares text; the others compare numbers.
If the last command's resultif errorlevel 1 (
…
) else (
…
)
Every command finishes with a number: 0 usually means it worked and anything else that it failed. After a choice block it is the number of the key pressed. "At least" and "less than" work anywhere; "exactly" and "not" don't update inside a loop or if block.
If a variable is setif defined FILE (
…
) else (
…
)
Checks whether a variable has anything in it, for example whether a file was dropped on the script.
If a program is runningtasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" >nul
if not errorlevel 1 (
…
) else (
…
)
Checks the running programs for one by its .exe name.
If running as administratornet session >nul 2>&1
if not errorlevel 1 (
…
) else (
…
)
Checks whether the script was started with "Run as administrator".
Needs administratornet session >nul 2>&1
if errorlevel 1 (
echo Please right-click this file and choose "Run as administrator".
pause
exit /b 1
)
Stops with a message if the script wasn't started with right-click › Run as administrator. Put it near the top of scripts that change system settings.
Ask for administratornet session >nul 2>&1
if errorlevel 1 (
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
If the script isn't running as administrator it asks Windows to run it again as admin (the usual yes/no prompt) and closes the non-admin copy.
Label (a spot to jump to):startMarks a spot in the script that "Jump to" and "Run a section" blocks can go to.
Jump to a labelgoto startCarries on running from the label with that name. Jumping back up to an earlier label makes a loop.
Jump to the endgoto :eofJumps to the end of the script, or back from a section started with "Run a section".
Run a sectioncall :showRuns the part of the script under a label, then comes back here when it reaches "Jump to the end". Words after it arrive in the section as %1, %2…
Repeat forever:loop_b1
…
timeout /t 60 /nobreak >nul
goto loop_b1
Runs the blocks inside again and again until the window is closed. The wait stops it hogging the CPU.
If the last command failedif errorlevel 1 (echo Something went wrong.& pause & exit /b 1)A quick check after a command: if it failed, show a message and end the script.
Group(
…
)
Keeps blocks together in brackets, which lets you send the output of all of them to one file (use the output option).
Loops 8
BlockCodeWhat it does
For each filefor %%F in (*.txt) do (
…
)
Runs the blocks inside once per matching file. Inside, %%F is the file name; %%~nF is the name without extension, %%~xF the extension, %%~fF the full path, %%~zF the size.
For each file in all subfoldersfor /r "%USERPROFILE%\Pictures" %%F in (*.jpg) do (
…
)
Like "For each file" but also looks inside every subfolder.
For each folderfor /d %%D in (*) do (
…
)
Runs once per folder that matches, like every folder in the current one (*).
Countfor /l %%N in (1,1,10) do (
…
)
Repeats with a number going up (or down with a negative step). Repeat 10 times = from 1 to 10 by 1.
For each word in a listfor %%X in (google.com github.com) do (
…
)
Runs once for every item in a list separated by spaces, like a list of site names or file types.
For each line of a filefor /f "usebackq delims=" %%L in ("list.txt") do (
…
)
Reads a text file and runs once per line (blank lines are skipped).
For each line a command printsfor /f "delims=" %%L in ('dir /b') do (
…
)
Runs a command and goes through what it prints, one line at a time. Write | as ^| inside.
Split lines into partsfor /f "tokens=2 delims=:" %%A in ('ipconfig ^| findstr IPv4') do (
…
)
Goes through lines (of a command's output in single quotes, or a "file" in quotes) and cuts each one at the characters you choose. tokens=2 takes the second part; tokens=1,2 gives %%A and %%B.
Files & folders 35
BlockCodeWhat it does
Go to a foldercd /d "%USERPROFILE%\Downloads"Makes a folder the current one, so later commands work there. /d also switches drive.
Go to the script's foldercd /d "%~dp0"Makes the folder the .bat file is saved in the current one. Useful because "Run as administrator" starts scripts in C:\Windows\System32.
Go to a folder (remember the old one)pushd "\\NAS\Share"Like cd, but remembers where you were so "Go back" can return. Also works with network paths like \\server\share.
Go backpopdReturns to the folder you were in before the last pushd.
Make a folderif not exist "%USERPROFILE%\Desktop\New folder\" md "%USERPROFILE%\Desktop\New folder"Creates a folder, plus any missing folders above it. Skips it quietly if it already exists.
Delete a folderrd /s /q "%TEMP%\old-stuff"Deletes a folder and everything in it, without asking and without the Recycle Bin. Double-check the path!
Delete filesdel /q /f "%TEMP%\*.tmp"Deletes files (wildcards like *.tmp work). They skip the Recycle Bin.
Empty a folderdel /q /f /s "%TEMP%\*" >nul 2>&1
for /d %%D in ("%TEMP%\*") do rd /s /q "%%D" >nul 2>&1
Deletes everything inside a folder but keeps the folder itself. Files in use are skipped.
Copy filescopy /y "report.txt" "%USERPROFILE%\Desktop\"Copies one file, or many with a wildcard, into a folder or to a new name.
Copy a whole folderrobocopy "%USERPROFILE%\Documents" "D:\Backup\Documents" /e /r:1 /w:1 /np /nfl /ndlCopies a folder with everything in it, skipping files that are already up to date, which makes it the best way to back up. Mirror also deletes files from the copy that are gone from the original.
Copy folders (xcopy)xcopy "C:\Source" "D:\Target\" /e /i /yThe older way to copy folders. robocopy is usually better, but xcopy is fine for quick copies.
Move filesmove /y "*.jpg" "Pictures\"Moves files or a folder somewhere else.
Renameren "old.txt" "new.txt"Renames a file or folder. The new name is only a name, not a path. Wildcards work: *.jpeg to *.jpg.
Write a line to a fileecho Backup finished %DATE% %TIME%>>"log.txt""Write" starts the file fresh, "Add" puts the line at the end. Leave the text empty to add a blank line.
Show a filetype "notes.txt"Prints the contents of a text file in the window.
List filesdir "." /bLists the files in a folder. Bare gives just the names, which is easier to save to a file.
Folder treetree "." /aDraws the folders inside a folder as a tree.
Hide, show or lock a fileattrib +h "secret.txt"Changes a file's attributes: hidden files don't show in Explorer by default, read-only files can't be changed.
Make a linkmklink /j "C:\Games\Saves" "D:\Saves"Makes a shortcut-like link that programs treat as the real thing. A junction links folders and doesn't need admin; symbolic links usually do.
Zip a foldertar -a -c -f "Project.zip" "Project"Packs a folder into a .zip using tar, which comes with Windows 10 and 11.
Unzipif not exist "Unzipped\" md "Unzipped"
tar -x -f "download.zip" -C "Unzipped"
Unpacks a .zip into a folder (the folder must exist).
Delete files older than…forfiles /p "%USERPROFILE%\Downloads" /s /m *.* /d -30 /c "cmd /c if @isdir==FALSE del /q @path" 2>nulDeletes files that haven't changed in a number of days, including in subfolders. Great for clearing out old logs or downloads.
Search text in filesfindstr /i /c:"error" "*.log"Finds lines that contain some text. Prints each matching line, or just the file names.
Compare two filesfc "old.txt" "new.txt"Shows the differences between two files. The result is 0 when they match.
Sort linessort "names.txt" /o "sorted.txt"Sorts the lines of a text file A to Z.
File checksumcertutil -hashfile "download.iso" SHA256Works out a file's hash to check a download wasn't corrupted or changed.
Copy to the clipboardecho|set /p="%CD%"| clipPuts some text on the clipboard so it can be pasted anywhere.
Copy a file's text to the clipboardclip < "notes.txt"Puts the whole text of a file on the clipboard.
Make a file of a set sizefsutil file createnew "test.bin" 104857600Creates an empty file of an exact size, for testing transfers or disk space.
Give permissionicacls "C:\Shared" /grant "Users:(OI)(CI)M" /tLets a user or group use a file or folder. (OI)(CI) makes it apply to everything inside a folder too.
Take ownershiptakeown /f "C:\OldFolder" /r /d yMakes you the owner of a file or folder you're locked out of. Needs Run as administrator.
Folder as a drive lettersubst X: "C:\Projects"Makes a folder appear as its own drive letter until you restart.
Find where a program iswhere pythonSearches the PATH for a program and prints where it lives. The result is 1 if it isn't found, so it also checks whether something is installed.
Open a folder in Explorerstart "" explorer "%USERPROFILE%\Downloads"Opens a File Explorer window on a folder.
Empty the Recycle Binpowershell -NoProfile -Command "Clear-RecycleBin -Force -ErrorAction SilentlyContinue"Empties the Recycle Bin on every drive.
Programs & services 16
BlockCodeWhat it does
Open a program or filestart "" "notepad.exe"Starts a program, opens a file with its usual app, or opens a website. "Wait" holds the script until it closes.
Open a websitestart "" "https://localscriptbox.com"Opens a web page in the default browser.
Close a programtaskkill /f /im "notepad.exe"Closes every copy of a program by its .exe name. "Force" closes it even if it is frozen or asking to save.
List running programstasklistShows the running programs, optionally only ones whose name matches.
Wait until a program closes:wait_b1
tasklist /fi "imagename eq game.exe" | find /i "game.exe" >nul
if not errorlevel 1 (
timeout /t 10 /nobreak >nul
goto wait_b1
)
Checks every few seconds and carries on once the program is no longer running.
Run another .batcall "other-script.bat"Runs another batch file and comes back here when it finishes (without call, the other script would take over and never return).
Run a PowerShell commandpowershell -NoProfile -ExecutionPolicy Bypass -Command "Get-Date"Runs one line of PowerShell, for things batch can't do on its own. Use single quotes inside it.
Install or update appswinget install --id Mozilla.Firefox -e --accept-package-agreements --accept-source-agreements --silentUses winget, the app installer built into Windows 10 and 11, to install, update or remove apps by their ID (like Mozilla.Firefox).
Update every appwinget upgrade --all --accept-package-agreements --accept-source-agreementsUpdates every app that winget knows a newer version of.
Run an installer quietlymsiexec /i "setup.msi" /qn /norestartInstalls a .msi package with no windows or questions.
Start or stop a servicenet stop "Spooler"Starts or stops a Windows service (like Spooler, the printer queue). Needs Run as administrator.
Service start typesc config "SysMain" start= demandChanges whether a service starts with Windows. Needs Run as administrator.
Schedule a taskschtasks /create /tn "My backup" /tr "\"%USERPROFILE%\Desktop\backup.bat\"" /sc DAILY /st 21:00 /fAdds a task to Task Scheduler so a program or script runs by itself.
Delete a scheduled taskschtasks /delete /tn "My backup" /fRemoves a task from Task Scheduler.
Restart Explorertaskkill /f /im explorer.exe >nul
start explorer.exe
Restarts the taskbar and desktop, which fixes a frozen taskbar or applies some settings.
Run a Linux command (WSL)wsl ls -laRuns a command inside WSL, if a Linux distro is installed.
System & power 25
BlockCodeWhat it does
Shut down or restartshutdown /s /t 60Shuts down or restarts the PC after a delay. Programs are closed, so unsaved work is lost. Cancel with the "Cancel a shutdown" block or shutdown /a.
Cancel a shutdownshutdown /aCancels a shutdown or restart that is counting down.
Sleep, hibernate, lock or sign outrundll32.exe user32.dll,LockWorkStationPuts the PC to sleep, hibernates it, locks the screen or signs out.
Turn the screen offpowershell -NoProfile -Command "(Add-Type -MemberDefinition '[DllImport(\"user32.dll\")] public static extern int SendMessage(int h,int m,int w,int l);' -Name W -PassThru)::SendMessage(-1,0x0112,0xF170,2)" >nulTurns the monitor off (moving the mouse turns it back on).
Power planpowercfg /setactive SCHEME_MINSwitches the Windows power plan.
Hibernation on or offpowercfg /hibernate offTurns hibernation on or off. Off frees disk space the size of your RAM. Needs Run as administrator.
Never sleep (plugged in)powercfg /change standby-timeout-ac 0Sets how long the PC waits before sleeping when plugged in. 0 means never.
Battery reportpowercfg /batteryreport /output "%USERPROFILE%\Desktop\battery-report.html"Saves a laptop battery health report as a web page.
System informationsysteminfoPrints Windows version, install date, uptime, RAM, updates and more.
Who am IhostnamePrints the PC's name or the signed-in user.
Repair system filessfc /scannowChecks Windows' own files and replaces broken ones. Takes a while. Needs Run as administrator.
Repair the Windows imageDISM /Online /Cleanup-Image /RestoreHealthDownloads fresh copies of damaged Windows files from Windows Update. Run it before sfc when sfc can't fix things. Needs Run as administrator.
Check a diskchkdsk C:Scans a drive for file system errors. Fixing the C: drive happens at the next restart. Needs Run as administrator.
Optimize a drivedefrag C: /ORuns Windows' drive optimizer: TRIM for SSDs, defragmenting for hard drives. Needs Run as administrator.
Change a registry settingreg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "HideFileExt" /t REG_DWORD /d "0" /fAdds or changes a value in the registry. HKCU settings are for you; HKLM is for the whole PC and needs Run as administrator.
Read a registry settingreg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" /v "AppsUseLightTheme"Prints a value from the registry.
Delete a registry settingreg delete "HKCU\Software\MyApp" /v "OldSetting" /fRemoves a value from the registry. Leave the name empty to delete the whole key. Careful!
Back up a registry keyreg export "HKCU\Software\MyApp" "%USERPROFILE%\Desktop\backup.reg" /ySaves a registry key to a .reg file you can double-click later to restore it.
Create a restore pointpowershell -NoProfile -Command "Checkpoint-Computer -Description 'Before changes' -RestorePointType MODIFY_SETTINGS"Makes a System Restore point so you can undo changes. Needs Run as administrator and System Protection turned on.
Sync the clocknet start w32time >nul 2>&1
w32tm /resync /force
Makes Windows check its clock with the internet time server right now. Needs Run as administrator.
Apply group policygpupdate /forceApplies group policy changes right away instead of waiting.
Back up driversif not exist "D:\DriverBackup\" md "D:\DriverBackup"
pnputil /export-driver * "D:\DriverBackup"
Copies every installed third-party driver into a folder. Needs Run as administrator.
Disk CleanupcleanmgrOpens Windows Disk Cleanup.
Time zonetzutil /s "Eastern Standard Time"Changes the time zone. Run tzutil /l to list the names.
Recent errorswevtutil qe System /q:"*[System[(Level=2)]]" /c:10 /rd:true /f:textShows the newest error messages from the System event log.
Network 18
BlockCodeWhat it does
Pingping -n 4 1.1.1.1Checks whether a site or device answers and how fast. The result is 1 when nothing answered.
If onlineping -n 1 -w 2000 1.1.1.1 | find "TTL=" >nul
if not errorlevel 1 (
…
) else (
…
)
Pings a reliable server once and runs the right blocks depending on whether it answered.
Trace the routetracert -d google.comShows every hop between you and a server, to find where a connection slows down.
Look up a domainnslookup localscriptbox.comAsks DNS for a domain's IP address.
IP settingsipconfig /allShows your network settings, or clears the DNS cache, or gets a fresh IP address from the router.
Open connectionsnetstat -anoLeave the box empty to see everything. Lists open network connections and listening ports with the process ID using each.
Download a filecurl -L -o "file.zip" "https://example.com/file.zip"Downloads a file from the internet with curl, which comes with Windows 10 and 11.
Map a network drivenet use Z: "\\NAS\Share" /persistent:yesConnects a shared folder as a drive letter. "Keep" reconnects it after a restart.
Remove a network drivenet use Z: /delete /yDisconnects a mapped drive.
Saved Wi-Fi networksnetsh wlan show profilesLists the Wi-Fi networks this PC remembers.
Wi-Fi passwordnetsh wlan show profile name="MyWiFi" key=clear | findstr /c:"Key Content"Shows the saved password for one Wi-Fi network (under Key Content).
Set DNS serversnetsh interface ip set dns name="Wi-Fi" static 1.1.1.1Changes the DNS server for a network adapter (names like Wi-Fi or Ethernet). Needs Run as administrator.
Automatic DNSnetsh interface ip set dns name="Wi-Fi" dhcpPuts an adapter's DNS back to whatever the router hands out. Needs Run as administrator.
Open a firewall portnetsh advfirewall firewall add rule name="Game server" dir=in action=allow protocol=TCP localport=25565Lets other devices connect to a port on this PC, like for a game server. Needs Run as administrator.
Reset networkingnetsh winsock reset
netsh int ip reset
Resets Winsock and TCP/IP, a common fix for broken internet. Needs Run as administrator and a restart.
Test a portpowershell -NoProfile -Command "if ((Test-NetConnection 'localscriptbox.com' -Port 443 -WarningAction SilentlyContinue).TcpTestSucceeded) { 'Open' } else { 'Closed' }"Checks whether a server accepts connections on a port.
MAC addressesgetmac /vLists the hardware (MAC) addresses of your network adapters.
Devices seen on the networkarp -aLists devices this PC has talked to on the local network, with their IP and MAC addresses.
Anything else 2
BlockCodeWhat it does
Any commandecho Anything goes hereType any command or line of batch you like, exactly as it should appear in the file.
Several linesecho one
echo two
Paste a chunk of batch code as it is.

Every Windows command

The "Windows command" block can run any of these 232 commands that come with Windows. Ones marked "window" open a program, so the block starts them with start "" and the script carries on without waiting.

Built into cmd 39
CommandExampleWhat it does
assocassoc .txtShows or changes which file type an extension belongs to.
breakbreakDoes nothing on Windows; kept so very old scripts still run.
callcall other.batRuns another batch file or a :label section and comes back afterwards.
cdcd /d "%USERPROFILE%"Shows or changes the current folder (chdir is the same command).
clsclsClears the window.
cmdcmd /c echo HelloStarts a new command prompt; /c runs one command then closes, /k keeps it open.
colorcolor 0ASets the window's background and text colors with two hex digits.
copycopy "a.txt" "b.txt"Copies files, or joins several into one with +.
datedate /tShows the date (/t), or sets it when run as administrator.
deldel /q "*.tmp"Deletes files (erase is the same command).
dirdir /bLists files and folders.
echoecho HelloPrints text, or turns command echoing on or off.
endlocalendlocalEnds a setlocal and throws away the variables set since.
exitexit /b 0Leaves the script (/b) or closes cmd, with an exit code.
forfor %%F in (*.txt) do echo %%FRepeats a command for files, folders, numbers, lines or command output.
ftypeftype txtfileShows or sets the program that opens a file type.
gotogoto labelJumps to a :label in the script.
ifif exist "file.txt" echo FoundRuns a command only when a condition is true.
mdmd "New folder"Makes folders, including missing parent folders (mkdir is the same).
mklinkmklink /j "Link" "Target"Makes symbolic links, hard links and folder junctions.
movemove "a.txt" "Folder\"Moves files or renames a folder.
pathpathShows or sets the list of folders cmd searches for programs.
pausepauseWaits for a key press.
popdpopdGoes back to the folder saved by pushd.
promptprompt $P$GChanges what the cmd prompt looks like.
pushdpushd "C:\Folder"Saves the current folder and goes to another, even a network share.
rdrd /s /q "Folder"Removes a folder, with /s everything inside it too (rmdir is the same).
remrem A noteA comment; the line is ignored.
renren "old.txt" "new.txt"Renames files or folders (rename is the same).
setset "NAME=value"Shows, sets or removes variables; /a does math, /p asks for input.
setlocalsetlocal EnableDelayedExpansionKeeps variable changes local to the script and can turn on !VAR! expansion.
shiftshiftMoves the script's arguments down one place, %2 into %1 and so on.
startstart "" "notepad.exe"Opens a program, file or website in its own window.
timetime /tShows the time (/t), or sets it when run as administrator.
titletitle My scriptSets the window title.
typetype "file.txt"Prints a text file.
ververShows the Windows version number.
verifyverifyShows or sets file-write verification (does nothing useful today).
volvol C:Shows a drive's label and serial number.
Files, folders & disks 38
CommandExampleWhat it does
attribattrib +h "file.txt"Shows or changes hidden, read-only, system and archive flags.
bcdbootbcdboot C:\Windows /s S:Copies boot files to a partition so Windows can start from it.
caclscacls "file.txt"Old way to view or change file permissions; use icacls instead.
chkdskchkdsk C:Checks a drive for file system errors and can fix them (/f).
chkntfschkntfs C:Shows or changes whether a drive gets checked at startup.
ciphercipher /w:C:\Encrypts files with EFS, or wipes free space so deleted files can't be recovered (/w).
compcomp "a.bin" "b.bin" /mCompares two files byte by byte.
compactcompact /c /s "Folder"Shows or changes NTFS compression on files and folders.
convertconvert D: /fs:ntfsConverts a FAT32 drive to NTFS without losing files.
defragdefrag C: /oOptimizes drives: TRIM for SSDs, defragmenting for hard drives.
diskpartdiskpart /s commands.txtManages disks, partitions and volumes. Powerful: it can wipe disks.
diskshadowdiskshadowManages volume shadow copies (on Windows Server).
expandexpand "file.cab" -F:* "Folder"Unpacks files from .cab archives.
extrac32extrac32 /e "file.cab"Another tool for unpacking .cab files.
fcfc "a.txt" "b.txt"Compares two files and shows the differences.
findfind /i "word" "file.txt"Finds lines containing a piece of text.
findstrfindstr /s /i "word" *.txtSearches files for text, with wildcards and patterns.
forfilesforfiles /p "C:\Logs" /d -30 /c "cmd /c echo @file"Runs a command on files picked by name or age.
formatformat E: /fs:exfat /qFormats a drive. Everything on it is erased.
fsutilfsutil volume diskfree C:Low-level file system tool: free space, test files, TRIM, hard links and more.
icaclsicacls "Folder" /grant Users:(OI)(CI)MShows, changes, saves or restores file and folder permissions.
labellabel E: BackupChanges a drive's name.
makecabmakecab "file.txt" "file.cab"Packs a file into a .cab archive.
manage-bdemanage-bde -statusTurns BitLocker drive encryption on or off and shows its status.
mountvolmountvolLists volumes and links them to drive letters or folders.
recoverrecover "file.txt"Rescues readable parts of a file from a damaged disk.
repair-bderepair-bde C: D: -rk F:\key.bekTries to get data back from a damaged BitLocker drive.
replacereplace "C:\New\*.*" "C:\Old" /uReplaces files in one folder with newer copies from another.
robocopyrobocopy "C:\From" "D:\To" /eCopies folders robustly, skipping up-to-date files; the best tool for backups.
sortsort "names.txt"Sorts lines of text.
substsubst X: "C:\Projects"Shows a folder as its own drive letter.
takeowntakeown /f "Folder" /r /d yMakes you the owner of files or folders.
tartar -a -c -f "out.zip" "Folder"Creates and unpacks .zip and .tar archives.
treetree /f /aDraws the folder structure as a tree.
vssadminvssadmin list shadowsLists and manages shadow copies used by System Restore and backups.
wbadminwbadmin get versionsWindows Backup from the command line.
wherewhere pythonFinds where a program or file is.
xcopyxcopy "C:\From" "D:\To\" /e /iCopies files and folders (robocopy is usually better).
Network 27
CommandExampleWhat it does
arparp -aShows the IP and MAC addresses of devices seen on the local network.
bitsadminbitsadmin /transfer job https://example.com/f.zip "%CD%\f.zip"Downloads files in the background (older; curl is simpler).
curlcurl -L -o "file.zip" https://example.com/file.zipDownloads files and talks to web servers and APIs.
fingerfinger user@hostAsks an old-style server about a user. Rarely used now.
ftpftp -s:commands.txt hostTransfers files with an FTP server.
getmacgetmac /vLists network adapters and their MAC addresses.
hostnamehostnamePrints the computer's name.
ipconfigipconfig /allShows network settings, clears the DNS cache, or renews the IP address.
nbtstatnbtstat -nShows NetBIOS names and connections, used by older Windows file sharing.
netnet useManages shares, mapped drives, users, groups and services (net use, net user, net start…).
netshnetsh wlan show profilesConfigures networking: Wi-Fi, firewall, IP addresses, proxies and more.
netstatnetstat -anoLists open connections and listening ports.
nslookupnslookup example.comLooks up a domain's IP address and other DNS records.
pathpingpathping example.comTraces the route to a server and measures loss at every hop.
pingping -n 4 1.1.1.1Checks whether a device or site answers, and how fast.
pktmonpktmon start --captureCaptures network packets for troubleshooting.
routeroute printShows or changes the IP routing table.
rpcpingrpcping -s serverTests the RPC connection to a server.
scpscp "file.txt" user@host:/home/user/Copies files to or from another computer over SSH.
sftpsftp user@hostTransfers files over SSH, interactively.
sshssh user@hostOpens a secure shell on another computer.
ssh-keygenssh-keygen -t ed25519Makes SSH keys for logging in without a password.
telnettelnet host 23Connects to a telnet server or tests a port (optional Windows feature).
tftptftp -i host get file.binTransfers a file with a TFTP server (optional Windows feature).
tracerttracert -d example.comShows each hop on the way to a server.
winrmwinrm quickconfigSets up Windows Remote Management.
winrswinrs -r:server ipconfigRuns a command on another PC through Windows Remote Management.
Users & security 12
CommandExampleWhat it does
auditpolauditpol /get /category:*Shows or changes which security events Windows logs.
certreqcertreq -new request.inf request.reqRequests certificates from a certificate authority.
certutilcertutil -hashfile "file.iso" SHA256Certificate tool, also handy for file hashes and Base64.
cmdkeycmdkey /listLists, adds or removes saved passwords for servers and shares.
gpresultgpresult /rShows which group policies apply to this PC and user.
gpupdategpupdate /forceApplies group policy changes right away.
klistklistLists Kerberos tickets on a domain-joined PC.
ksetupksetupConfigures Kerberos settings.
logofflogoffSigns the current user out.
runasrunas /user:Administrator cmdRuns a program as another user.
seceditsecedit /export /cfg policy.infExports, analyzes or applies security policy settings.
whoamiwhoami /allShows the signed-in user, their groups and privileges.
Programs & services 14
CommandExampleWhat it does
msiexecmsiexec /i "setup.msi" /qnInstalls, repairs or removes .msi packages.
openfilesopenfiles /queryLists files opened over the network (or locally once turned on).
qprocessqprocessLists running processes with their session (same as query process).
regsvr32regsvr32 "file.dll"Registers or unregisters a DLL or control.
rundll32rundll32 user32.dll,LockWorkStationRuns a function inside a DLL, used for things like locking the screen.
scsc queryLists, starts, stops and configures services.
schtasksschtasks /queryCreates, runs, changes and deletes scheduled tasks.
taskkilltaskkill /im notepad.exeCloses programs by name or process ID.
tasklisttasklistLists running programs.
timeouttimeout /t 5Waits a number of seconds.
tskilltskill notepadEnds a process by name or ID (older than taskkill).
waitforwaitfor /t 60 GoSignalWaits for, or sends, a named signal between scripts or PCs.
wingetwinget upgrade --allInstalls, updates and removes apps.
wusawusa "update.msu" /quiet /norestartInstalls or removes Windows update packages (.msu).
System, power & repair 21
CommandExampleWhat it does
bcdeditbcdedit /enumViews and changes boot settings. Careful: a mistake can stop Windows starting.
bootcfgbootcfg /queryOld tool for boot settings; bcdedit replaced it.
dismdism /Online /Cleanup-Image /RestoreHealthRepairs and services the Windows image, and adds or removes features.
driverquerydriverquery /vLists installed drivers.
fltmcfltmcLists the file system filter drivers, like antivirus.
msinfo32start "" msinfo32 /report "%USERPROFILE%\Desktop\info.txt"System Information, as a window or a saved report. (window)
pnputilpnputil /enum-driversAdds, removes, lists and exports driver packages.
powercfgpowercfg /batteryreportPower plans, sleep settings, battery and energy reports.
pwlauncherpwlauncher /disableTurns the Windows To Go startup options on or off.
reagentcreagentc /infoManages the Windows Recovery Environment.
regreg query HKCU\EnvironmentReads, adds, deletes, exports and imports registry settings.
reginiregini changes.iniChanges the registry from a script file.
sfcsfc /scannowChecks Windows' system files and repairs broken ones.
shutdownshutdown /s /t 60Shuts down, restarts, hibernates or signs out, with a timer.
systeminfosysteminfoShows the Windows version, hardware, updates and uptime.
systemresetstart "" systemresetOpens Reset this PC. (window)
tzutiltzutil /gShows or sets the time zone.
verifierstart "" verifierDriver Verifier, for stress-testing drivers. Can cause crashes on purpose. (window)
w32tmw32tm /resyncWindows Time service: syncs the clock and shows its status.
winsatwinsat formalRuns Windows' built-in hardware performance tests.
wmicwmic os get captionOld WMI command line; being removed from Windows, use PowerShell instead.
Remote Desktop & sessions 11
CommandExampleWhat it does
changechange logon /queryChanges Remote Desktop server settings for logons, ports or install mode.
msgmsg * Time for a breakSends a popup message to a user or session.
mstscstart "" mstsc /v:serverOpens Remote Desktop Connection. (window)
queryquery userShows sessions, users and processes on a Remote Desktop server.
quserquserLists signed-in users and their sessions.
qwinstaqwinstaLists Remote Desktop sessions.
rdpsignrdpsign /sha256 hash "file.rdp"Signs a Remote Desktop (.rdp) file.
rwinstarwinsta 2Resets (ends) a Remote Desktop session.
shadowshadow 2Watches or controls another user's Remote Desktop session.
tscontscon 2 /dest:consoleConnects to another session.
tsdiscontsdisconDisconnects a session without signing out.
Logs & performance 9
CommandExampleWhat it does
eventcreateeventcreate /t information /id 100 /l application /d "Backup done"Writes your own entry into an event log.
lodctrlodctr /rRebuilds or registers performance counters.
logmanlogman queryCreates and manages performance and trace logs.
relogrelog in.blg -f csv -o out.csvConverts performance logs, for example to CSV.
tracerpttracerpt trace.etl -o report.xmlTurns trace logs into reports.
typeperftypeperf "\Processor(_Total)\% Processor Time" -sc 5Prints performance counters like CPU use.
unlodctrunlodctr serviceRemoves a program's performance counters.
wecutilwecutil esManages event log subscriptions.
wevtutilwevtutil qe System /c:10 /rd:true /f:textReads, exports and clears event logs.
Console & scripting 15
CommandExampleWhat it does
chcpchcp 65001Changes the text code page, like 65001 for UTF-8.
choicechoice /c YN /m "Continue"Waits for one key from a list.
clipclip < "file.txt"Copies text to the clipboard.
cscriptcscript //nologo script.vbsRuns a VBScript or JScript file in the console.
doskeydoskey ls=dir $*Makes command shortcuts (macros) and recalls past commands.
helphelp dirShows help for a cmd command.
iexpressstart "" iexpressBuilds self-extracting installers. (window)
modemode con: cols=100 lines=30Sets the window size, keyboard speed and serial ports.
moremore < "file.txt"Shows long output one screen at a time.
powershellpowershell -NoProfile -Command "Get-Date"Runs Windows PowerShell commands or scripts.
printprint "file.txt"Sends a text file to a printer.
pwshpwsh -NoProfile -Command "Get-Date"Runs PowerShell 7, if it is installed.
setxsetx NAME "value"Saves a variable permanently for new windows and programs.
wscriptwscript script.vbsRuns a VBScript or JScript file with popup windows.
wslwsl ls -laRuns Linux commands with the Windows Subsystem for Linux.
Open a Windows tool 46
CommandExampleWhat it does
appwiz.cplstart "" appwiz.cplOpens Programs and Features (uninstall programs). (window)
calcstart "" calcOpens Calculator. (window)
certmgr.mscstart "" certmgr.mscOpens your certificates. (window)
charmapstart "" charmapOpens Character Map, for symbols and special characters. (window)
cleanmgrstart "" cleanmgrOpens Disk Cleanup. (window)
compmgmt.mscstart "" compmgmt.mscOpens Computer Management. (window)
controlstart "" controlOpens Control Panel (or a page of it, like control printers). (window)
desk.cplstart "" desk.cplOpens display settings. (window)
devmgmt.mscstart "" devmgmt.mscOpens Device Manager. (window)
diskmgmt.mscstart "" diskmgmt.mscOpens Disk Management. (window)
dxdiagstart "" dxdiag /t "%USERPROFILE%\Desktop\dxdiag.txt"DirectX Diagnostic Tool: graphics, sound and driver info, as a window or a report. (window)
eventvwrstart "" eventvwrOpens Event Viewer. (window)
explorerstart "" explorer "%USERPROFILE%\Downloads"Opens File Explorer, optionally on a folder. (window)
firewall.cplstart "" firewall.cplOpens Windows Defender Firewall. (window)
gpedit.mscstart "" gpedit.mscOpens the Local Group Policy Editor (Pro and up). (window)
inetcpl.cplstart "" inetcpl.cplOpens Internet Options. (window)
lusrmgr.mscstart "" lusrmgr.mscOpens Local Users and Groups (Pro and up). (window)
magnifystart "" magnifyOpens Magnifier. (window)
main.cplstart "" main.cplOpens Mouse properties. (window)
mdschedstart "" mdschedOpens Windows Memory Diagnostic, which tests RAM after a restart. (window)
mmcstart "" mmcOpens the Microsoft Management Console. (window)
mmsys.cplstart "" mmsys.cplOpens Sound settings (playback and recording devices). (window)
ms-settings:start "" ms-settings:Opens Settings; add a page after the colon, like ms-settings:windowsupdate. (window)
msconfigstart "" msconfigOpens System Configuration (startup and boot options). (window)
mspaintstart "" mspaintOpens Paint. (window)
narratorstart "" narratorStarts Narrator, the screen reader. (window)
ncpa.cplstart "" ncpa.cplOpens Network Connections (adapters). (window)
notepadstart "" notepad "file.txt"Opens Notepad, optionally with a file. (window)
optionalfeaturesstart "" optionalfeaturesOpens Turn Windows features on or off. (window)
oskstart "" oskOpens the on-screen keyboard. (window)
perfmonstart "" perfmon /relOpens Performance Monitor; /rel opens Reliability Monitor. (window)
powercfg.cplstart "" powercfg.cplOpens Power Options. (window)
regeditstart "" regeditOpens Registry Editor. (window)
resmonstart "" resmonOpens Resource Monitor. (window)
rstruistart "" rstruiOpens System Restore. (window)
secpol.mscstart "" secpol.mscOpens Local Security Policy (Pro and up). (window)
services.mscstart "" services.mscOpens Services. (window)
sigverifstart "" sigverifChecks for unsigned system files. (window)
sndvolstart "" sndvolOpens the Volume Mixer. (window)
snippingtoolstart "" snippingtoolOpens the Snipping Tool. (window)
sysdm.cplstart "" sysdm.cplOpens System Properties (PC name, restore, environment variables). (window)
taskmgrstart "" taskmgrOpens Task Manager. (window)
taskschd.mscstart "" taskschd.mscOpens Task Scheduler. (window)
timedate.cplstart "" timedate.cplOpens Date and Time. (window)
wf.mscstart "" wf.mscOpens the advanced firewall settings. (window)
winverstart "" winverShows the About Windows box with the exact version. (window)

Batch File Builder FAQ

What is a batch file?

A batch file is a plain text file ending in .bat that holds a list of commands for cmd, the Windows command prompt. Double-clicking it runs the commands one after another, so anything you'd type into cmd can be saved and run again with one click.

Does it have every command?

The "Every Windows command" group has the commands built into cmd plus the command-line tools that come with Windows, each with a short explanation, and the other groups have ready-made blocks for the things scripts do most. Anything that isn't there, like a program you installed yourself, goes in an "Any command" block.

Why doesn't my variable change inside a loop or if block?

cmd reads a whole bracketed block before running any of it, so %NAME% inside it is filled in once with the value from before the block. Add the "Keep variables local" block with delayed expansion ticked near the top, then write !NAME! instead of %NAME% inside the block. The builder warns you when this happens.

Why do loop variables have two percent signs?

Inside a .bat file a loop variable is written %%F. Typed straight into cmd it would be %F, but in a file cmd needs the second % to tell it apart from a normal variable. The loop blocks write it for you.

Some blocks need Run as administrator. How?

Right-click the .bat file and choose Run as administrator. Or add the "Ask for administrator" block at the top and the script asks Windows for permission by itself when it starts.

What's the difference between .bat and .cmd?

Almost nothing on Windows 10 and 11. Both run in cmd. You can type either ending in the file name box.

Does it work on Mac or Linux?

No, batch files are Windows only. Mac and Linux use shell scripts, which are a different language.

Is my script uploaded anywhere?

No. The blocks and the code are built in your browser and saved only in this browser's storage. The download comes straight from your browser too.

Ready-made scripts

Rather start from one that's already done? Each of these 69 scripts has its own page where you pick a few options and download the .bat.

Shutdown, power & sleep10
Clean up & free space12
Files & folders16
Network & internet10
Repair & system info11
Apps & automation10