Microsoft Windows > Batch Scripting

Batch 101

Disable command echoing

@echo off

Fix working directory when script is started as Administrator

When you run a script as Administrator on Windows, the CWD is set by default to “system32”. This script resets it to the correct folder.

cd /D %~dp0

Make sure the script was ran as Admin

SET "ADM=" &bcdedit >NUL 2>&1
IF NOT "%ERRORLEVEL%"=="1" SET "ADM=Y"
IF NOT DEFINED ADM echo The script was not ran as admin!

Hide errors

mkdir existing 2> nul

Variables

Pad an integer with zeros

If we want 6 numbers :

set n=1337
set padded=00000%n%
set padded=%padded:~-6%
echo %padded%

Note that we put 5 zeros, not 6. Note also that if the number is longer than 6 digits, the first digits will be lost.

Get the date/time in a format that's usable in a filename

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set datetime=%datetime:~0,8%-%datetime:~8,6%
echo %datetime%

Outputs : 20160415-161703

Environment variables

What Name Example
Windows directory
echo %WinDir%
C:\Windows\
Path to search into
echo %PATH%
C:\lorem;C:\ipsum
Application data folder (Roaming)
echo %AppData%
C:\Users\cfr\AppData\Roaming
Application data folder (Local)
echo %LocalAppData%
C:\Users\cfr\AppData\Local
Current directory
echo %cd%
C:\foobar
Computer name
echo %ComputerName%
PC12345
Error level
echo %ErrorLevel%
0
Date
echo %DATE%
25.09.15
Time
echo %TIME%
12:55:19,11
OS
echo %OS%
Windows_NT
Program files (32-bits)
echo %ProgramFiles(x86)%
C:\Program Files (x86)
Program files (64-bits)
echo %ProgramFiles%
C:\Program Files
Random number in [0, 32767]
echo %RANDOM%
1337
Temporary folder
echo %TEMP%
C:\Users\cfr\AppData\Local\Temp
Username
echo %UserName%
cfr
Domain
echo %UserDomain%
WORKGROUP
Session root
echo %UserProfile%
C:\Users\cfr

Flow

Wait for one minute

timeout /t 60 /nobreak > nul

Wait for 500 milliseconds

sleep.vbs
WScript.Sleep WScript.Arguments(0)
sleep.bat
%windir%\system32\cscript.exe sleep.vbs 500 > nul

End the current batch

goto :eof

Foreach

set machines=(machine1, machine2, machine3)
for %%G in %machines% do (
   echo ** %%G **
)

For i=0 to N

set N=10
for /L %%G in (0,1,%N%) do (
   echo %%G
)

(Note : N is included!)

Endless loop

SET i=1
:loop
echo %i%
timeout /t 1 /nobreak > nul
SET /A i += 1
GOTO loop

Use "set" in FOR loops

This can be done by turning on the delayed expansion and using the ! notation.

@echo off
setlocal enabledelayedexpansion
for /L %%G in (1,1,10) do (
   set super=it_works_%%G
   echo !super!
)

Do something in case of error

This checks if the error level is different from 0 :

IF ERRORLEVEL 1 echo Do something!

This checks if the error level is exactly equal to 1 :

IF %ERRORLEVEL% EQU 1 echo Do something!

The difference between ERRORLEVEL and %ERRORLEVEL% is explained on this page.

User inputs

Prompt for a variable

set /p variable="Value of variable: "
echo %variable%

Ask a Yes/No question

SET /P AREYOUSURE=Are you sure (Y/[N])?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
rem Yes...
:END
rem Yes & No...

Check if there are N parameters

if "%~N"=="" echo There are not enough parameters!

File manipulation

Delete a folder and its content

rmdir /S /Q "path/to/root/"

Note that it removes the root folder too.

Copy a folder and its content

xcopy /si "path/to/folder1" "path/to/folder2"

Append to file

A line of text

echo Salut >> file.txt

A new line

echo. >> file.txt

Equivalent of unix "touch"

This sets the modification date to now.

copy /b file.ext +,,

Check if path exists

if not exist d:\folder\ goto nofolder
echo Do something only if folder exists!
 
:nofolder
echo Do the rest!

Count how many folders there is

for /f %%a in ('dir /b /d Z:\^|find /c /v "" ') do set count=%%a
echo %count% folder(s^)

Other interactions

Open URL in default browser

start "" http://www.google.com

Start a program in a new window

start "" "path/to/your/app.exe" -param1 -param2

Change the wallpaper

Print/export