2009/05/31

Batch File Basic Math Trainer: Math in Batch Files


Is it possible to write a math game in Batch? Yes. But it is not as easy to work with as in true programming languages. The code in this game should help anyone who wants to learn more about working with numbers in a batch file.

@echo off
title Batch Basic Math Quiz
color 1f

:title
CLS
echo.
echo Welcome to Batch Basic Math Quiz
echo http://ScriptingMadness.blogspot.com
echo.
echo + - * /
echo.
echo.
echo Pick a number:
echo.
echo 1 for Addition
echo 2 for Subtraction
echo 3 for Multiplication
echo 4 for Division
echo 5 for All the Above
echo 6 to Exit
echo.
set /p topic= :
goto begin
REM #####################################
REM #####################################
REM #####################################
REM ###### MULTI ##############
:multi
set /a int1=%random%%%100+1
set /a int2=%random%%%100+1
set question=%int1%*%int2%
set /a answer=%question%
echo.
echo.
set /p guess=%int1% x %int2% =
set RightWrong=Wrong
if %guess%==EXIT goto title
if %guess%==Exit goto title
if %guess%==exit goto title
if %guess%==%answer% set RightWrong=Correct
rem Score
set return=MultiScore
goto Score
:MultiScore
rem ----
echo.
echo = %answer%
echo.
echo.
echo You are %RightWrong%. Points: %score%
echo --------------------------------------------------------------
goto next
REM #####################################
REM #####################################
REM ###### Add #########
:add
set /a int1=%random%%%100+1
set /a int2=%random%%%100+1
set question=%int1%+%int2%
set /a answer=%question%
echo.
echo.
set /p guess=%int1% + %int2% =
set RightWrong=Wrong
if %guess%==EXIT goto title
if %guess%==Exit goto title
if %guess%==exit goto title
if %guess%==%answer% set RightWrong=Correct
rem Score
set return=AddScore
goto Score
:AddScore
rem ----
echo.
echo = %answer%
echo.
echo.
echo You are %RightWrong%. Points: %score%
echo --------------------------------------------------------------
goto next
REM #####################################
REM #####################################
REM #####################################
REM ###### Sub ##############
:sub
set /a int1=%random%%%100+1
set /a int2=%random%%%100+1
set question=%int1%-%int2%
set /a answer=%question%
echo.
echo.
set /p guess=%int1% - %int2% =
set RightWrong=Wrong
if %guess%==EXIT goto title
if %guess%==Exit goto title
if %guess%==exit goto title
if %guess%==%answer% set RightWrong=Correct
rem Score
set return=SubScore
goto Score
:SubScore
rem ----
echo.
echo = %answer%
echo.
echo.
echo You are %RightWrong%. Points: %score%
echo --------------------------------------------------------------
goto next
REM #####################################
REM #####################################
REM #####################################
REM ###### Div ##############
:div
set /a int1=%random%%%100+1
set /a int2=%random%%%20+1
set question=%int1%/%int2%
set /a answer=%question%
set /a remainder="(%int1%) %% (%int2%)"
if %remainder%==0 goto SkipRemainder
set answer=%answer%_%remainder%
:SkipRemainder
echo.
echo Seperate Answer and Remainder with an Underscore "_".
echo.
echo.
set /p guess=%int1% / %int2% =
set RightWrong=Wrong
if %guess%==EXIT goto title
if %guess%==Exit goto title
if %guess%==exit goto title
if %guess%==%answer% set RightWrong=Correct
rem Score
set return=divScore
goto Score
:divScore
rem ----
echo.
echo = %answer%
echo.
echo.
echo You are %RightWrong%. Points: %score%
echo --------------------------------------------------------------
goto next
REM #####################################
REM #####################################
REM #####################################
:begin
set score=0
echo.
echo --------------------------------------------------------------
echo TO RETURN TO MAIN MENU, TYPE EXIT
echo.
echo Reach a score of 20 to Pass. Try not to use a calculator!
echo #For a great flash cards maker, try flash-card-it.blogspot.com
echo --------------------------------------------------------------
echo.
:next
set all="false"
if %topic%==1 goto add
if %topic%==2 goto sub
if %topic%==3 goto multi
if %topic%==4 goto div
if %topic%==5 goto all
if %topic%==6 exit
goto title
REM #####################################
REM #####################################
REM #####################################
:Score
if %RightWrong%==Wrong set ScoreMath=%score%-1
if %RightWrong%==Correct set ScoreMath=%score%+1
set /a score=%ScoreMath%
if %score%==20 goto win
goto %return%
REM #####################################
REM #####################################
REM #####################################
:win
CLS
echo ------------------------------------------
echo - -
echo - CONGRATULATIONS!!! YOU PASSED! -
echo - -
echo ------------------------------------------
echo.
echo Score: 20
echo.
echo.
echo.
pause
cls
goto title
REM #####################################
REM #####################################
REM #####################################
:all
set /a pick=%random%%%4+1
if %pick%==1 goto add
if %pick%==2 goto sub
if %pick%==3 goto multi
if %pick%==4 goto div
goto error
REM #####################################
REM #####################################
REM #####################################
:error
echo The program has encountered an error!
echo It will now close
echo.
echo.
exit



The code is a bit disorganized, but it should still be fairly readable. The interesting command for working with numbers in a batch file is the set /a command. I had some trouble getting the command to work properly if I tried to use a varible and an operator like this:

set /a answer=%var1%+%var2%

It seems to only work if working with a single variable that already contains the problem like so.

set question=%var1%+%var2%
set /a answer=%question%

The above code works perfectly. Another important thing to remember when working with math in batch files is the modulus operator. It uses the % sign. The problem arises when trying to use the modulus operator on two varibles. It ends up looking like this:

%var1% % %var2%

Unfortunately, this code does not work. The batch file ignores the % operator. This can be solved by using two instead of one.

%var1% %% %var2%

Not pretty, but plenty functional.


Wish List:

Here are some ideas to further improve the script.
  • Create levels of difficulty. Right now the problems are all fairly simple.
  • Create a Accuracy Counter.
  • Clean up the interface

2009/05/27

Create a Batch File Chat Room


It is possible to build a full featured chat room using only the Window's batch programming language. It may not be pretty, but it gets the job done.

The idea is simple. Everyone writes to the same file. Collect input from the user and write it to that file. Then read that file to the screen to see what anyone else has said. Here is my code:

@echo off
rem: Matthew Merchant ScriptingMadness.blogspot.com
rem ###### TITLE SCREEN ############
title Batch Chat Room
color f0
echo.
echo Welcome to Office Chat Room.
echo.
echo Commands:
echo type CLS to clear the chat log.
echo type EXIT to quit the chat room.
echo just hit enter to update screen.
echo.
set /p username=What is your name?
echo %username% has joined. >> log.dat
cls
goto CHATLOOP
REM ############################




REM ########## CHAT LOOP ##########
set lastmessage=""

:CHATLOOP
cls
type log.dat
echo.
echo.
set /p message=Say:

rem set message checker value
set thismessage="%message%"

rem check for exit
if %thismessage% == "EXIT" echo %username% has left the chat room. >> log.dat
if %thismessage% == "EXIT" exit
rem -----------------

rem check for clear
if %thismessage% == "CLS" echo %username% has cleared the chat log. > log.dat
if %thismessage% == "CLS" set message=Empty
if %thismessage% == "CLS" set lastmessage="Empty"
if %thismessage% == "CLS" goto CHATLOOP
rem ------------------

rem check for same message as last time
if %thismessage% == %lastmessage% goto CHATLOOP

rem if all checks out, go ahead and post this message
echo %username%: %message% >> log.dat

rem save value for next test
set lastmessage="%message%"

goto CHATLOOP
REM ################################



Pretty basic stuff. The hard part was implementing my two features. The first feature was CLS. This command clears the chat log by writing to it with the > symbol. This is helpful when the chat log gets too big because it slows the program down. The second feature is the EXIT command. This gracefully shuts the batch chat program down after sending a exit message to the other users.


Wish List:

I would have liked this program to update in real time. This would be possible if two batch files were used. One could be used for input, and another could be used for displaying the chat log. I can't figure out a way to do it with one batch file.

It might also be neat to create an HTA chat room that works in a similar way. This would present the user with a nicer interface, and it could also be updated in real time.

2009/05/23

Creating Keyboard Macros in VBScript



Creating a keyboard macro in VBScript is an easy and highly portable way to automate tasks for any Windows machine. It is portable because every modern installation of Windows will have the Windows Scripting Host (WSH) installed, and that is all that is required to run the VBScript source code.

But I have found that writing a macro in VBScript can be time consuming. Truthfully, when starting from scratch it is much easier to use a language dedicated to macro building such as Autoit. However, by using a VBScript macro template you can easily create macros that are much more human readable, even to a complete computer novice. Use the link above to download one that I have created.

By using the template, I have been able to teach a few of the users at my work how to automate some of the tasks they were performing manually everyday. I have even found that I prefer my template's language over the commands available to Autoit. But I do realize it is rather limited.

Again, here is the link to the VBScript keyboard macro template that I have created.

2009/05/22

How to Program a Batch File Alarm Clock

I had lost my cell phone, and it was lunch time. I wanted to take a short nap, but I had no way wake myself up. It is a sad fact that when Windows XP was developed, they forgot to include a built in alarm clock. Here is a batch file solution to that problem that I whipped up.
CLS
@echo off
color f0
title Batch Alarm Clock
echo.
echo.
echo.
echo Use the 24 hour clock: example 15:00 for 3:00PM
echo.
set /p a=Set Alarm:
CLS
echo.
echo.
echo Alarm is set for %a%.
echo.
echo You may minimize this window.

REM #### ALARM LOGIC ####
REM alarm will only sound for one minute.

:top
if %time:~0,5% == %a% echo ALARM!!! Close this window to stop.
goto top

Copy this code into a text file and name it Alarm.bat

The code is pretty simple to follow. The important parts are the set /p command where I gather the desired time and then the if statement at the bottom. The :~0,5% part of the time variable means that only a piece of that variable is being used. I don't care to match up the exact time down to the millisecond. The funny looking symbols that are being echoed later on that same line are actually CTRL+G symbols. They caused the computers internal alarm to beep for the entire minute that matches with the time you enter.

It might be ugly, but it works great. I was able to get that nap, and the alarm woke me up just fine!

2008/07/02

Windows Batch File Programming: Part one

The most basic aspect of network monitoring is checking to see if a host is online via pinging it. This can be done manually. Any task that can be done manually can be automated. The first thing I do is write out the steps of how it would be preformed manually. Let us say we wanted to check 3 websites to see if they are up. If we were to do this manually we would have to:


1. Open a command prompt.
2. Type Ping 4.2.2.2
3. Review the results.
4. Type Ping 4.2.2.15. Review the results.
6. Type Ping 198.128.50.50
7. Review the results.

This is not too hard, but what if we had 50 hosts to check? That could get tiring. This is where automation/scripting steps in and takes the reins. You could write a simple script that does the same exact thing. It would look something like this in Windows Batch:

ping 4.2.2.2
ping 4.2.2.1
ping 192.168.50.50


This typed into notepad and saved as pinger.bat file would perform the same task much more easily, however let’s try something a little more powerful. I would hate to type ping for all 50 hosts. One of the favorite acronyms of most professional programmers I talk to is this. DRY! It means don't repeat yourself! We used the ping command 3 times. What if we had to ping 100 hosts? We can save ourselves some typing by using an iteration/loop. After all, is that not the whole idea of scripting? Windows Batch includes something we can use to do this. It is called the for loop.

First you need to move the group of hosts to another text file. Make sure you keep it in the same directory as your batch file. It is nice to put it all in its own folder. Think of it as the workshop for your project. Open notepad and type the following:

4.2.2.1
4.2.2.1
192.168.50.50

Save this file as "host.txt" This should do it for the ip/host list. You can feel free to add as many hosts or ip addresses as you like. This list is way more maintainable than the method from before. It only includes the hosts are you interested in. It can also be used in other batch files or programs. This is all in the spirit of DRY!Now you will need to modify your pinger batfile. Open it in notepad and clear everything out. We can now perform our query with a single line of code. Type the following:

For /F "tokens=*" %%i IN ("host.txt") DO ping %%i

That’s it!! Save it. Execute it. Admire it! You have improved the pinger application with a script. But what the hell does it mean? For a closer look you can open the command prompt and type the following command for /? . The for command is very powerful and the best way to learn is to experiment with it and the different switches.Now you have a pinger utility that can ping all items in a list. While that is way better than doing it manually for a large number of hosts, we still only automated half of the process. Can you guess what the second part is? That’s right. I'm so proud of you to have made it this far. It is the review the results part. Programming is supposed to promote laziness. I have better things to do at my help desk than constantly ping the network to make sure it is up. We will go over methods to automate that part in the next edition of this article. Thanks for reading. I hope you were able to get something out of it.


ScriptingMadness.Blogspot.com © 2009 || Privacy Policy