Batch Script Code Snippets

Below are some useful Batch Script code snippets for use in everyday projects.

Sometimes it may be necessary to accept input from the user so that it can be utilised within a script. This can be achieved using the '/p' option with the 'set' command for a variable. Here, the input is placed into a variable called 'user' and then displayed as part of a greeting.

:: Stop output to the screen unless 'echo' is used.
@echo off

:: Set greeting variable and accept user input.
set greeting=Hello
set /p user="Please enter your name: "

:: Display the greeting.
echo %greeting% %user%

:: Keep command window open until a key is pressed.
pause

When diagnosing network connectivity issues the 'ipconfig' command can be used to display TCP/IP and network adapter information, 'ping' shows whether a host is reachable or not, and 'tracert' returns routing information. Here, the results of all of these are output to a text file.

:: Stop output to the screen unless 'echo' is used.
@echo off

:: View network connection details.
ipconfig /all >> c:\demo\results.txt

:: Check if Google.com is reachable.
ping google.com >> c:\demo\results.txt

:: Run a traceroute to check the route to Google.com.
tracert google.com >> c:\demo\results.txt