Show Menu
Cheatography

Windows Batch Scripting Cheat Sheet (DRAFT) by

Windows Batch Scripting

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Settings

SETLOCAL ENABLE­DEL­AYE­DEX­PANSION
Enable delayed enviro­nment variable expansion.

For loop

FOR %variable IN (set) DO command [comma­nd-­par­ame­ters]
FOR /D
FOR /R
FOR /L
Loop against a set of files
FOR /F ["op­tio­ns"] %%para­meter IN (filen­ame­set­|"Text String­") DO command
options:
delims=xxx - The delimiter charac­ter(s) (default = a space)
skip=n - A number of lines to skip at the beginning of the file. (default = 0)
eol=; - Character at the start of each line to indicate a comment (default = semicolon)
tokens=n - Specifies which numbered items to read from each line (default = 1)
usebackq
1) Use the alternate quoting style:
2) Use double quotes for long file names in "­fil­ena­mes­et".
3) Use single quotes for 'Text string to process'
4) Use back quotes for command to process

Examples:
FOR %%a IN (%*) DO ECHO %%a

Choice

**Creates a pause for 2 seconds
CHOICE /T 2 /D Y > NUL
 

Batch Parameters Modifiers

%~1 - expands %1 removing any surrou­nding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file

The modifiers can be combined to get compound results:
%~dp1 - expands %1 to a drive letter and path only
%~nx1 - expands %1 to a file name and extension only

Changing a file extension to create a log file name:
SET MyLogF­ile­=%~­dpn­0.log
 

Service Control

Status query a service on a machine
SC localhost QUERY WPCSvc

Stop a service on a machine
SC \\SERV­ERNAME STOP WPCSvc