Batch 101


Windows Batch Scripting 101

Variables

To list variables defined on a system use the set command,set
To assign a string to a variable use the set command and do not wrap quotes around the string. 

for example
set ping=ping 127.0.0.1


Then to execute the variable type, %ping%


To assign arithmetic operations in a variable use the set /a.

for example
set /a four=2 + 2%four%


Local Variables and Global Variables


Local Variables are known locally within a script
Global variables are variables which are known by the command shell. 
Global variables are system wide, and are distinct by having capital letters


To assign user input to a variable use the set /p command.

for example
set /p var=Enter Your Variable
var will now contain the string which was entered by a user.

To assign local variables type SETLOCAL, 
then define the variable
to close a local variable type ENDLOCAL or exit the script

for example
SETLOCAL
set var=This Is A Local Variable
echo %var%
ENDLOCAL


To assign a global variable type set followed by defining the variable 

for example
set var=This Is A Global Variable
echo %var%

Command Line Arguments

Arguments that gets passed to a batch script, are special variables defined without declaring %var%
these arguments are defined by a single % followed by the argument (ordinal position)

Windows only support 9 arguments, to provide additional arguments a shift command can be used.

The Shift command will pop the first argument from the list of arguments and shift the rest over by 1

for example
@echo off
echo %1
echo %2
echo %3
shift
echo %1 //this argument gets poped off the list
echo %2 //this gets moved over to ordinal position 1
echo %3 //this gets moved over to ordinal position 2

Parameter Extensions

When an argument is used to supply a filename then the following extended syntax can be applied:

we are using the variable %1 (but this works for any parameter)


  • %~f1 Expand %1 to a Fully qualified path name - C:\utils\MyFile.txt
  • %~d1 Expand %1 to a Drive letter only - C:
  • %~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which will be interpreted as an escape character by some commands.
  • %~n1 Expand %1 to a file Name without file extension or path - MyFile 
  • or if only a path is present, with no trailing backslash, the last folder in that path.
  • %~x1 Expand %1 to a file eXtension only - .txt
  • %~s1 Change the meaning of f, n, s and x to reference the Short 8.3 name (if it exists.) 
  • %~1   Expand %1 removing any surrounding quotes (")
  • %~a1 Display the file attributes of %1
  • %~t1 Display the date/time of %1
  • %~z1 Display the file size of %1
  • %~$PATH:1 Search the PATH environment variable and expand %1 to the fully qualified name of the first match found.

reference: https://ss64.com/nt/syntax-args.html

The modifiers above can be combined:

  • %~dp1 Expand %1 to a drive letter and path only
  • %~sp1 Expand %1 to a path shortened to 8.3 characters
  • %~nx2 Expand %2 to a file name and extension only


for example
@echo off
set /p arg1=Enter The Full Location Of The File In Question:
for %i in %arg1% do set location=~f1 
for %i in %arg1% do set fileattrib=%~a1
for %i in %arg1% do set timestamp=%~t1
for %i in %arg1% do set size=%~z1
echo "Printing Information"
echo %location%
echo %fileattrib%
echo %timestamp%
echo %size%

To apply parameter extensions to other arguments just change its ordinal position 

Tips
When writing a batch script start by setting its layout:
type, SETLOCAL ENABLEEXTENSIONS 

The ENABLEEXTENSIONS command grants access to standard environment variables.


Standard (built-in) Environment Variables


ALLUSERSPROFILEC:\ProgramData
APPDATAC:\Users\{username}\AppData\Roaming
CDYThe current directory (string).
ClientNameYTerminal servers only - the ComputerName of a remote host.
CMDEXTVERSIONYThe current Command Processor Extensions version number. (NT = "1", Win2000+ = "2".)
CMDCMDLINEYThe original command line that invoked the Command Processor.
CommonProgramFilesC:\Program Files\Common Files
COMMONPROGRAMFILES(x86)C:\Program Files (x86)\Common Files
COMPUTERNAME{computername}
COMSPECC:\Windows\System32\cmd.exe or if running a 32 bit WOW - C:\Windows\SysWOW64\cmd.exe
DATEYThe current date using same region specific format as DATE.
ERRORLEVELYThe current ERRORLEVEL value, automatically set when a program exits.
FPS_BROWSER_APP_PROFILE_STRING
FPS_BROWSER_USER_PROFILE_STRING

Internet Explorer
Default
These are undocumented variables for the Edge browser in Windows 10.
HighestNumaNodeNumberY (hidden)The highest NUMA node number on this computer.
HOMEDRIVEYC:
HOMEPATHY\Users\{username}
LOCALAPPDATAC:\Users\{username}\AppData\Local
LOGONSERVER\\{domain_logon_server}
NUMBER_OF_PROCESSORSYThe Number of processors running on the machine.
OSYOperating system on the user's workstation.
PATHUser and
System
C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem;{plus program paths}
PATHEXT
.COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF; .WSH; .MSC
Determine the default executable file extensions to search for and use, and in which order, left to right.
The syntax is like the PATH variable - semicolon separators.
PROCESSOR_ARCHITECTUREYAMD64/IA64/x86 This doesn't tell you the architecture of the processor but only of the current process, so it returns "x86" for a 32 bit WOW process running on 64 bit Windows. See detecting OS 32/64 bit
PROCESSOR_ARCHITEW6432=%PROCESSOR_ARCHITECTURE% (but only available to 64 bit processes)
PROCESSOR_IDENTIFIERYProcessor ID of the user's workstation.
PROCESSOR_LEVELYProcessor level of the user's workstation.
PROCESSOR_REVISIONYProcessor version of the user's workstation.
ProgramW6432=%ProgramFiles%(but only available when running under a 64 bit OS)
ProgramDataC:\ProgramData
ProgramFilesC:\Program Files or C:\Program Files (x86)
ProgramFiles(x86) 1C:\Program Files (x86)   (but only available when running under a 64 bit OS)
PROMPTCode for current command prompt format,usually $P$G
C:>
PSModulePath%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\
PublicC:\Users\Public
RANDOMYA random integer number, anything from 0 to 32,767 (inclusive).
%SessionName%Terminal servers only - for a terminal server session, SessionName is a combination of the connection name, followed by #SessionNumber. For a console session, SessionName returns "Console".
SYSTEMDRIVEC:
SYSTEMROOTBy default, Windows is installed to C:\Windows but there's no guarantee of that, Windows can be installed to a different folder, or a different drive letter.
systemroot is a read-only system variable that will resolve to the correct location.
NT 4.0, Windows 2000 and Windows NT 3.1 default to C:\WINNT
TEMP and TMPUser VariableC:\Users\{Username}\AppData\Local\Temp
Under XP this was \{username}\Local Settings\Temp
TIMEYThe current time using same format as TIME.
UserDnsDomainY
User Variable
Set if a user is a logged on to a domain and returns the fully qualified DNS domain that the currently logged on user's account belongs to.
USERDOMAIN{userdomain}
USERDOMAIN_roamingprofileThe user domain for RDS or standard roaming profile paths. Windows 8/10/2012 (or Windows 7/2008 with Q2664408)
USERNAME{username}
USERPROFILE%SystemDrive%\Users\{username}
This is equivalent to the $HOME environment variable in Unix/Linux
WINDIR%WinDir% pre-dates Windows NT and seems to be superseded by %SystemRoot%
Set by default as windir=%SystemRoot%
%windir% is a regular variable and can be changed, which makes it less robust than %systemroot%
Reference: https://ss64.com/nt/syntax-variables.html

Return Codes


Return codes are stored in the %ERRORLEVEL% standard environment variable. 
To check for the return code of a command use an if statement

for example
if %ERRORLEVEL% NEQ (not equal to zero) 0 (echo "Operation Failed") || (echo "Operation Completed Successfully")

if %ERRORLEVEL% EQU 0 (equal to zero) 0 (echo "Operation Completed Successfully") || (echo "Operation Failed") 


if %ERRORLEVEL% NEQ 0 ( echo "Operation Failed" )ELSE( echo "Operating Completed Successfully" )

When combining an ELSE statement with parenthesis, always put the parenthesis on the same line as ELSE. ) ELSE (   This is because CMD does a rather primitive one-line-at-a-time parsing of the command.

Conditional Execution Commands

  • && - executes another command if the first command was a success
  • & - execute another command example: ping 127.0.0.1 & nc 192.168.1.10 4444 
  • || - execute another command only if the first command failed


Redirections and Pipes

Windows includes File Descriptors which are referenced by numbers:
0 = stdin (input)
1 - stdout (output) 
2 - stderr (error)

Redirection symbols  include:

  • < - The < symbol causes file to be fed to the program as input.
  • > - The > symbol causes the program's output to be sent to the following file or device
  • .>> - The >> symbol causes the program's output to be appended to the file or device.
  • | - The | symbol (the pipe) causes the output of the preceding program to be sent to the following program.

These commands can be used redirect output to a file

for example
dir >> file.txt dir > file.txt


To redirect output and error messages to a file. Simple specify the number which references the file descriptor, such as 2>&1 

for example
ping 127.0.0.1 >> results.txt 2>&1


To redirect contents from a file to a command use < for example:sort < file.txt
To suppress output messages, redirect stdout to NUL

for example
ping 127.0.0.1 > NUL


To create a new file with a redirector, use TYPE CON 

for example
TYPE CON > file.txt


IF Statements

The if statement checks to see if a condition is met and then performs a command 
The command IF /I i enables incase insensitive.


IF - Arithmetic Conditions

  • EQU - Equal To
  • NEQ - Not Equal To
  • LSS - Less Than
  • LEQ - Less Than OR Equal To
  • GTR - Greater Than
  • GEQ - Greater Than Or Equal To

for example
SET /A var=1
IF /I "%var%" EQU "1" 
ECHO fail

IF /I "%var%" NEQ "0" 
ECHO success

IF /I "%var%" GEQ "1" 
ECHO greater than or equal to 1

IF /I "%var%" LEQ "1" 
ECHO less than or equal to 1 


IF - String conditions

  • == - perform the command if the two strings are equal.
  • NOT - perform the command if the condition is false. 
  • EXIST - perform the command if the condition is true.

for example
IF [NOT] EXIST filename execute a command
IF [NOT] EXIST filename (command) ELSE (command)
IF EXIST "temp.txt" ECHO found
IF NOT EXIST "temp.txt" ECHO not found
IF EXIST "temp.txt" (ECHO found) ELSE (ECHO not found)

IF Statement used to match a text string


IF [/I] [NOT] item1==item2 execute command     
IF /I EXIST var=string echo "True"   
IF /I NOT EXIST var=string echo "False"
SET var=Hello, World!
IF "%var%"=="Hello, World!" ECHO found
IF /I "%var%"=="hello, world!" ECHO found

IF Statement used for Error Checking

IF %ERRORLEVEL% NEQ 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found
IF /I "%ERRORLEVEL%" NEQ "0" ECHO execution failed


Loops

Looping through commands require the use of labels. These labels are called by the goto command

for example
@echo off
set return=next
goto start
:start
execute command
goto %return%
:next
execute command
goto end
:end
EXIT /B 0

For Statements

When using for loops from a command line use a single % sign. When using a batch file use double %% signs, 


Processing Files with a For Loop

for %i in ( ) do command


for example
FOR %I IN (%USERPROFILE%\*) DO @ECHO %I


Processing Files Recursively 

for /R %i in ( ) do command


For example
FOR /R "%TEMP%" /D %I IN (*) DO @ECHO %I


Processing Directories
for /D %i in ( ) do command

For example
FOR /D %I IN (%USERPROFILE%\*) DO @ECHO %I


Perform a for loop using a range of numbers

for /L %i in ( ) do command
The range is defined as (start, modifer, end) 

For example

  • To count from 1 to 254 use (1,1,254)
  • To count by multiple of 2 use (1,4,254)
  • To count down use (254,-1,1)


for /L %i in (1,1,254) do ping 192.168.1.%i 2> null

Processing Results from a Command

For /F %i in ( command to process) do command


Functions

To define a function in windows, labels are used and are called using the CALL command. 
Then at the end of the function EXIT /B 0 is used to return.
When writing a function, write them in the bottom


for example
dir /s *.txt | call find
:find
FOR /F "tokens=* USEBACKQ" %%F IN (findstr "pwd creds") DO (SET interesting_files=%%F)
echo %interesting_files%
EXIT /B 0


Arguments
Command Arguments can be read and validated with an IF statement

For example
set file=%~a1
IF %file% == h (attrib -h -r -s /s /d %file% EXIT /B 0)

Reading User Input

To prompt user into entering input and then to assign the input into a variable type SET /P and then use > to redirect the input into a variable. 

For example
:confirm
SET /P "Continue [y/n]>" %confirm%
FINDSTR /I "^(y|n|yes|no)$" > NUL || GOTO: confirm



Comments

Popular Posts