Determining if a number is odd or even using a batch file

Our challenge recently was seperating the reboots of our citrix servers to ensure that half of our farm is always available. This is particularly useful if you are a 24/7 house and need to know exactly what servers restart and when they restart.

So to begin, our server names consist of “servername00xx” where xx is the number of the server, the task at hand was to ensure that 0001, 0003, 0005 etc restarted on one night and 0002, 0004, 0006 etc restarted the second night. To do this i needed to use the system variable “hostname” and read the last digit in the name to determine if the number was odd or even.

To get determine whether a number is odd or even i used the following logic. If you divide an even number by 2 then multiply it by two you will get the same number back, e.g. 8/2 = 4, 4*2 = 8, 8 is equal to 8 .

An odd number in batch is treated as follows 9/2=4, 4*2=8 ,9 is NOT equal to 8.

Rem Begining Logic Check for even or odd server
for /f “tokens=1-2 delims=00″ %%a in (‘hostname’) do set compnumber=%%b
set /a divnumber=%compnumber%/2
set /a sum=%divnumber%*2

With the above excerpt, i set three variables, %compnumber% (which is the number after the 00), divnumber (a variable for the result of the computernumber divided by two) and sum, which is the resulting divnumber * 2.

This divides compnumber by 2 and multiplys divnumber by 2 setting the resulting number to sum.

Rem Running if checks
if %compnumber% NEQ %sum% goto odds
if %compnumber% EQU %sum% goto evens

This next step is our determiner:

If the number divided by two and multiplied by two is not the same as the original number, the number is odd, the if statement then sends the script to the odds labeled portion of our script.

If the number divided by two and multiplied by two is the same as the original number, well you get the idea, its even and jumps down.

<—Do something for odd servers here—>

<—Do something for even servers here—>

Related Posts

Monitoring Storage disk queue’s and IO with ... Here's one that used to bother me alot. The problem usually went as follows: "Your XenApp servers have very high disk queue's and IO" "What's causin...
Silently installing the Citrix Edgesight ActiveX p... Just a really quick blog post on how to silently install the reporting agent inside your environment. Log into a server / client without the EdgeSigh...
Removing Screen Resolution and Personalize shell e... While working in a XenApp 6 proof of concept I came accross this little feature and decided its time to share it! When a user right clicks on the d...

2 Comments About “Determining if a number is odd or even using a batch file

  1. Josh

    Would the following code also work in the above situation?

    set /a modulo = “%compnumber% %% 2″
    if %modulo% == 0 (
    rem Do something for even servers here
    ) else (
    rem Do something for odd servers here


Leave a Reply