MIR_EGAL123's ULTIMATE BATCH FILE CODING TUTORIAL FOR NOOBS
Hello and welcome to my tutorial. Today I am going to give you an easy to follow guide to coding batch files, which I believe is the best way to start your coding "journey". I will start with simple commands, then progress onwards until you, too, are a formidable batch file coder yourself. Continue to the next page to view the start of the tutorial.
**Note: Right now, this is an NGU exclusive post! You will see this on no other websites, and if you do, It is not me posting it. I want to keep this exclusive to you guys only, so don't post this to other sites please.
[multipage=Part 1: The Most Important Commands You Need To Know]
Well, I see that you have decided to take part on this journey of batch coding. I am just going to let you know beforehand that some of the stuff after this can get annoying if you have errors in your code, so don't give up! Anyways, let's get on with the tutorial.
First you are going to want to open up a normal text file in notepad. Then you are going to want to type something like this:
That "Echo" command is the best way to communicate to the person using your batch file. It will display a message on the screen with whatever you typed. Now you can go ahead and save by changing the .txt to a .bat, and making sure it is on "All Files" as the save option:
Now run your batch file, wherever you saved it. Did you see a flash on your screen? That was the batch file coming up and disappearing almost instantly. The reason for this is because there was no command to make it wait for the user to close it. What you are going to need to do is right click on the batch file and click on "Edit":
Now you are going to want to type the word "pause" on the line afterwards, like so:
The command pause waits for the user to press a certain button or use a certain function (in this case, any key on the keyboard). Now you can save it again. Run your batch file again, and it should look something like this:
Oh gosh, another problem? Yes. This time the issue is that the batch program is displaying the directory of where the command is coming from. In my case, it is showing the path to the desktop, where I have the file saved. But there is a very easy fix to this. Open it up using the "Edit" option in the right click menu, and type "@echo off" a line BEFORE the "echo" command line:
This "@echo off" is the SINGLE MOST IMPORTANT COMMAND YOU WILL EVER USE IN A BATCH FILE EVER. Sorry about the all caps, I was just trying to get it through your head that it is the SINGLE MOST IMPORTANT COMMAND YOU WILL EVER USE IN A BATCH FILE EV.. fine, I'll stop now. There is a little more of an in-depth explanation I could give you here, but the easiest way to explain it is that it basically covers up that directory, so that you don't see the actual command being processed, and just the output. Alright, now that I am done explaining that to you, save your batch file and run it:
Success! You have made your first batch file. Doesn't matter at this point how complex it is, because at the end of this tutorial you'll be able to make a complex one yourself. On the next page, I will be talking about making your batch file wait a period of time, and also how to use user input to operate the commands you want.
[multipage=Part 2: Get the User Involved Too!]
Well, I see that you have managed to find your way to this section of the tutorial. Here I am going to be showing you how to get your batch file to have a time interval before displaying a message, and how to get user input to decide which command to execute. First we will start off by opening that batch file from before (Once again, using the "Edit" feature in the right click menu) and add in a line of code so it looks like this:
Basically what that ping code is doing is that it is working in the background (as in no text appears when the batch file has been ran), but it is taking longer to process, therefore causing a waiting period before the next command. I'll explain to you what each part of the command does.
ping - Sends 32 packets (default) of information to a certain IP or website (in this case, localhost)
localhost - This means the ping command is pinging your network
-n 2 - The -n 2 represents a variable for how many times you want to ping the selected IP or website (in this case, twice). If a decimal value is put (example: 1.5), it will perform 1 ping and cancel itself midway through the next ping.
> nul - When using the localhost part of the code, you need to make it choose a file to ping. By typing > nul, it doesn't create a new file, while > null does. This command can also be used to create new files with any extension you want.
Now, when you open up the batch file, you should notice a time delay from when the batch file opens and when the message appears in the window. If you do not, then you need to go back and edit the batch file to make sure you have the right syntax. For those who do not know, the definition of syntax is "The branch of linguistics that deals with the grammatical arrangement of words and morphemes in the sentences of a language or of languages in general." In coder's terms, an error in syntax means an error in your code.
We have now come to the point in this tutorial where I explain how to make this batch file of yours interactive with anybody that uses it. We can do this simply by using a modified pause command and a few IF statements. Don't worry, that may seem a little scary (), but I assure you it is a fairly easy task. Go to your batch file and edit it, and insert this code the way I do.
You should have noticed that the pause command has been removed, and in place is the set /p command. Why don't you go ahead and save it, then run it and see what it looks like?
If it looks like mine (minus the NextgenupdateFTW), then your code has worked! But this allows the user to write what they want. In my case i wrote NextgenupdateFTW. This command opens up a whole new world for possibilities. Before we get there, however, I am going to show you how the command works.
set /p - This basically sets the message that the pause command would normally show to something else.
MESSAGE= - This creates a variable for your pause message. This is primarily used when making batch files with multiple functions. That name "MESSAGE" can be changed to whatever you want, as it is the variable you are using.
What would you like to do today?: - This is just the message we want our custom pause command to show.
Now that we have all of that settled, let's get on to making it a little more complex. Go and edit your batch file with codes that look like this:
You will notice that I added a couple more things, and there are 2 new commands: IF and GOTO. I added in some text at the top for options. Once you have this code in, save it and run it. When you open it, if you type 1 or 2 it will do nothing, and that is because there are no functions set to be done when you type 1 or 2 and hit enter. First I will explain all of the new things that I added.
echo: - This is just a command that directs the custom pause command to the IF statements.
IF %QUESTION%==1 GOTO :1 - The IF is to say "if the user typed in 1 and hit enter, go to :1." This works because we used the QUESTION variable and put percentage signs around it, making the program recognize that it is infact a variable.
IF %QUESTION%==2 GOTO :2 - The same thin as above, except this time it is saying "if the user typed in 2 and hit enter, go to :2."
Now that we have that all sorted out, it is time to insert our functions into the areas labeled as :1 and :2.
Oh look, 2 new commands! I will quickly explain these new commands, then tell you how the whole thing will work when we run it, then we will test it out!
exit - Fairly self-explanatory, exits the program.
cls - This command clears the screen, so there is not too much clogging it up at one time.
Alright, now that I have explained some of those commands, I am going to tell you how this batch file should work. If the user types in 1 and hits enter, it should exit the program. If the user types in 2 and hits enter, it should clear the screen, and have 5 HI's appear on the screen. Time to test it out! Oh wait, at the :2 part of the batch file, make sure you have a pause at the end of the five echo commands! Otherwise it will just close out.
That is what it looks like on startup. I typed in 1 and it exited, but I obviously couldn't get a picture of that.
This is after typing in 2 and hitting enter.
If this is what happened to you, congrats! You have made your first user-involved batch file! From here on in, I cannot really guide you any further. You have a lot of the stuff you need to know for basic coding, but now it is up to you to figure out cool ways to incorporate certain commands. Don't worry though, because on later pages you will find a list of ALL commands you can use and what they are used for, some interesting commands they do not talk about, some examples of well-designed batch files I have seen, and how to convert your batch file to an executable (.exe). Thanks for staying and reading your tutorial. Any positive feedback is encouraged, as I want to know if I went in depth enough.
[multipage=Part 3: A List of Basic Batch File Commands]
Here are the basic commands that you can use in your batch file, and also you can build on these to get them to do cool functions (Source: [Only registered and activated users can see links. ])
ADDUSERS Add or list users to/from a CSV file
ARP Address Resolution Protocol
ASSOC Change file extension associations
ASSOCIAT One step file association
ATTRIB Change file attributes
BCDBOOT Create or repair a system partition
BOOTCFG Edit Windows boot settings
BROWSTAT Get domain, browser and PDC info
CACLS Change file permissions
CALL Call one batch program from another
CD Change Directory - move to a specific Folder
CHANGE Change Terminal Server Session properties
CHKDSK Check Disk - check and repair disk problems
CHKNTFS Check the NTFS file system
CHOICE Accept keyboard input to a batch file
CIPHER Encrypt or Decrypt files/folders
CleanMgr Automated cleanup of Temp files, recycle bin
CLEARMEM Clear memory leaks
CLIP Copy STDIN to the Windows clipboard.
CLS Clear the screen
CLUSTER Windows Clustering
CMD Start a new CMD shell
CMDKEY Manage stored usernames/passwords
COLOR Change colors of the CMD window
COMP Compare the contents of two files or sets of files
COMPACT Compress files or folders on an NTFS partition
COMPRESS Compress individual files on an NTFS partition
CON2PRT Connect or disconnect a Printer
CONVERT Convert a FAT drive to NTFS.
COPY Copy one or more files to another location
CSCcmd Client-side caching (Offline Files)
CSVDE Import or Export Active Directory data
DATE Display or set the date
DEFRAG Defragment hard drive
DEL Delete one or more files
DELPROF Delete NT user profiles
DELTREE Delete a folder and all subfolders
DevCon Device Manager Command Line Utility
DIR Display a list of files and folders
DIRUSE Display disk usage
DISKCOMP Compare the contents of two floppy disks
DISKCOPY Copy the contents of one floppy disk to another
DISKPART Disk Administration
DNSSTAT DNS Statistics
DOSKEY Edit command line, recall commands, and create macros
DSACLs Active Directory ACLs
DSAdd Add items to active directory (user group computer)
DSGet View items in active directory (user group computer)
DSQuery Search for items in active directory (user group computer)
DSMod Modify items in active directory (user group computer)
DSMove Move an Active directory Object
DSRM Remove items from Active Directory
ECHO Display message on screen
ENDLOCAL End localisation of environment changes in a batch file
ERASE Delete one or more files
EVENTCREATE Add a message to the Windows event log
EXIT Quit the current script/routine and set an errorlevel
EXPAND Uncompress files
EXTRACT Uncompress CAB files
FC Compare two files
FIND Search for a text string in a file
FINDSTR Search for strings in files
FOR /F Loop command: against a set of files
FOR /F Loop command: against the results of another command
FOR Loop command: all options Files, Directory, List
FORFILES Batch process multiple files
FORMAT Format a disk
FREEDISK Check free disk space (in bytes)
FSUTIL File and Volume utilities
FTP File Transfer Protocol
FTYPE Display or modify file types used in file extension associations
GLOBAL Display membership of global groups
GOTO Direct a batch program to jump to a labelled line
GPUPDATE Update Group Policy settings
HELP Online Help
iCACLS Change file and folder permissions
IF Conditionally perform a command
IFMEMBER Is the current user in an NT Workgroup
IPCONFIG Configure IP
KILL Remove a program from memory
LABEL Edit a disk label
LOCAL Display membership of local groups
LOGEVENT Write text to the NT event viewer
LOGMAN Manage Performance Monitor
LOGOFF Log a user off
LOGTIME Log the date and time in a file
MAPISEND Send email from the command line
MBSAcli Baseline Security Analyzer.
MEM Display memory usage
MD Create new folders
MKLINK Create a symbolic link (linkd)
MODE Configure a system device
MORE Display output, one screen at a time
MOUNTVOL Manage a volume mount point
MOVE Move files from one folder to another
MOVEUSER Move a user from one domain to another
MSG Send a message
MSIEXEC Microsoft Windows Installer
MSINFO Windows NT diagnostics
MSTSC Terminal Server Connection (Remote Desktop Protocol)
MV Copy in-use files
NET Manage network resources
NETDOM Domain Manager
NETSH Configure Network Interfaces, Windows Firewall & Remote access
NETSVC Command-line Service Controller
NBTSTAT Display networking statistics (NetBIOS over TCP/IP)
NETSTAT Display networking statistics (TCP/IP)
NOW Display the current Date and Time
NSLOOKUP Name server lookup
NTBACKUP Backup folders to tape
NTRIGHTS Edit user account rights
OPENFILES Query or display open files
PATH Display or set a search path for executable files
PATHPING Trace route plus network latency and packet loss
PAUSE Suspend processing of a batch file and display a message
PERMS Show permissions for a user
PERFMON Performance Monitor
PING Test a network connection
POPD Restore the previous value of the current directory saved by PUSHD
PORTQRY Display the status of ports and services
POWERCFG Configure power settings
PRINT Print a text file
PRINTBRM Print queue Backup/Recovery
PRNCNFG Display, configure or rename a printer
PRNMNGR Add, delete, list printers set the default printer
PROMPT Change the command prompt
PsExec Execute process remotely
PsFile Show files opened remotely
PsGetSid Display the SID of a computer or a user
PsInfo List information about a system
PsKill Kill processes by name or process ID
PsList List detailed information about processes
PsLoggedOn Who's logged on (locally or via resource sharing)
PsLogList Event log records
PsPasswd Change account password
PsService View and control services
PsShutdown Shutdown or reboot a computer
PsSuspend Suspend processes
PUSHD Save and then change the current directory
QGREP Search file(s) for lines that match a given pattern.
RASDIAL Manage RAS connections
RASPHONE Manage RAS connections
RECOVER Recover a damaged file from a defective disk.
REG Registry: Read, Set, Export, Delete keys and values
REGEDIT Import or export registry settings
REGSVR32 Register or unregister a DLL
REGINI Change Registry Permissions
REM Record comments (remarks) in a batch file
REN Rename a file or files
REPLACE Replace or update one file with another
RD Delete folder(s)
RMTSHARE Share a folder or a printer
ROBOCOPY Robust File and Folder Copy
ROUTE Manipulate network routing tables
RUN Start | RUN commands
RUNAS Execute a program under a different user account
RUNDLL32 Run a DLL command (add/remove print connections)
SC Service Control
SCHTASKS Schedule a command to run at a specific time
SCLIST Display NT Services
SET Display, set, or remove environment variables
SETLOCAL Control the visibility of environment variables
SETX Set environment variables permanently
SFC System File Checker
SHARE List or edit a file share or print share
SHIFT Shift the position of replaceable parameters in a batch file
SHORTCUT Create a windows shortcut (.LNK file)
SHOWGRPS List the NT Workgroups a user has joined
SHOWMBRS List the Users who are members of a Workgroup
SHUTDOWN Shutdown the computer
SLEEP Wait for x seconds
SLMGR Software Licensing Management (Vista/2008)
SOON Schedule a command to run in the near future
SORT Sort input
START Start a program or command in a separate window
SU Switch User
SUBINACL Edit file and folder Permissions, Ownership and Domain
SUBST Associate a path with a drive letter
SYSTEMINFO List system configuration
TASKLIST List running applications and services
TASKKILL Remove a running process from memory
TIME Display or set the system time
TIMEOUT Delay processing of a batch file
TITLE Set the window title for a CMD.EXE session
TLIST Task list with full path
TOUCH Change file timestamps
TRACERT Trace route to a remote host
TREE Graphical display of folder structure
TSSHUTDN Remotely shut down or reboot a terminal server
TYPE Display the contents of a text file
TypePerf Write performance data to a log file
USRSTAT List domain usernames and last login
VER Display version information
VERIFY Verify that files have been saved
VOL Display a disk label
WHERE Locate and display files in a directory tree
WHOAMI Output the current UserName and domain
WINDIFF Compare the contents of two files or sets of files
WINMSD Windows system diagnostics
WINMSDP Windows system diagnostics II
WINRM Windows Remote Management
WINRS Windows Remote Shell
WMIC WMI Commands
WUAUCLT Windows Update
XCACLS Change file and folder permissions
XCOPY Copy files and folders
:: Comment / Remark
[multipage=Part 4: Some Cool Functions]
In this section I will be listing a couple of interesting commands and variables. If I am missing anything that you would like to see, post it as a reply.
Let's start with variables you can use:
%random% - Creates a random number string.
%username% - Displays the username of the person using the batch file.
%userprofile% - The folder location of where the username would be (example: CUsers\%userprofile%\My Documents)
%windir% - Basically directs you to the "windows" folder.
%md% - Creates a folder with a random name in the directory of where you run the program.
Some other cool non-variable commands:
net user "username" "password" /add - Used to make a new user. I will put in a simple code where you can let the batch file user choose the username and password of the user without having to actually type the code:
@echo off Title .:: User Maker ::. color 5b echo ------------------- ping localhost -n 1 > nul set /p USR=What would you like the new user's name to be?: ping localhost -n 1 > nul set /p PWRD=What would you like the new user's name to be?: ping localhost -n 1.5 > nul echo . ping localhost -n 1.5 > nul echo .. ping localhost -n 1.5 > nul echo ... ping localhost -n 1.5 > nul echo .... ping localhost -n 1.5 > nul echo ..... ping localhost -n 1.5 > nul net user %USR% %PWRD% /add msg * Username: %USR% Password %PWRD% User created successfully!
GOTO :EOF - This command tells the batch file to go to the end of it. Because there is nothing at the end of a batch file, it exits the program. Easier to do than making a whole new label just for 1 command.
Once again, post anything you think I should of put in, and I will gladly edit this post with credits to you.
[multipage=Part 5: Example of some Cool Batch Files]
AsianInvasion: [Only registered and activated users can see links. ]
Me: [Only registered and activated users can see links. ]
Masta-blasta117: [Only registered and activated users can see links. ]
[multipage=Part 6: Compiling Your Batch File to an Exe]
Well, I see you have made your way into this section, where I am going to show you an easy to use program that can help you with compiling your batch file to an exe. Before we start, you are going to need to download this installer that I made here: [Only registered and activated users can see links. ] (virus scan: [Only registered and activated users can see links. ]). Once you have downloaded that, we can begin. Once extracted, the folder should look like this:
Go into that folder, and there will be three files in there: The actual program, the help file (.chm) and the settings.ini configuration file. Alright, I know you are itching to do it, so open up the program. It will have an interface like this:
Now, before you do anything, I am going to explain what each option does.
Visibility - Whether you want your batch file to be visible or not. This can be good for prank batch files that shut down the computer.
Temporary Files - This option allows you to choose whether it keeps temporary files on the computer it is being used on, or that they are deleted when the program is exited.
Working Directory - Basically asks you if, for example, you had your batch file opening up multiple programs or files, it would choose where the programs/files are located (whether they are temporary or permanent)
Encryption - Allows you to encrypt your batch file with a password, so only people you trust can use it. Basically leecher defense.
Add Administrator Manifest - Runs the exe you compiled in administrator mode.
Overwrite Existing Files - If the user has the batch or any of the files associated with the batch file, they will be overwritten every time.
Add Decompiler - Adds a decompiler to your exe so it will go back to each seperate part of the file, and any files associated with it.
"Include" Tab - Includes a file to be compiled into the final exe. This would be used for batch files that operate using other files that no other computer may have (a certain picture or text file, perhaps)
"Versioninformations" Tab - Allows you to put a custom .ico file for the icon, and allows you to set information for the exe, so that when it is hovered over you can see it, like a description or product name.
Now that we have gotten through all that, you can hit that "..." button in the top right. Browse for your batch file that you made, and open it. Select any options you want with it, and hit the second, lower "..." button to choose the location where the compiled exe will be. Finally, hit the "Compile" button. A box should pop up on your screen for a short while, then dissapear. You should now have something like this:
And when you open it up, it should look something like this:
If so, congrats! You have successfully converted your batch file to an exe. Any questions about the compiler, ask me in a reply to this thread.