Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What I need to do is add a few lines to an existing batch file so that it acts differently depending on the machine name.

We have a standardised naming scheme where the first three letters of the machine name indicate the machine type and location. For three of these machine prefixes I want to run a command, for the rest I don't.

What I've got so far is that a command like this will find the characters in the machine name and either return the name, or return nothing depending on whether it matches:


And using a loop like this will do the same thing but for multiple names:


What I haven't figured out is how to use the output from either of those in a IF statement or something similar. Can anyone help me out?

share|improve this question
up vote 5 down vote accepted

Pull the first three characters out of the machine name first, with something like:

SET Name=%computername%
SET FirstThreeChars=%computername:~0,3%

Then run through your IF loop using the FirstThreeChars variable.

share|improve this answer
Ah brilliant, that's what I was missing. What's the colon tilde bit there, is that a substring type thing or a simple regex? I''ve put in your two lines followed by this bit to run the command: FOR %%A IN (UKD UKL USD) DO IF %%A==%FirstThreeChars% RunMyCommand and all is good :) – GAThrawn Dec 8 '09 at 11:38
Yes, it's a substring. I was trying to do something very similar with a date string to pull out the day/month/year separately, and this finally did the job (I hate Windows Batch). The first number is where to start from, and the second is the number of characters after that to grab. – RainyRat Dec 8 '09 at 11:41
In fact to further simplify the whole thing can be written on one line as: FOR %%A IN (UKD UKL USD) DO IF %%A==%computername:~0,3% RunMyCommand thanks for pointing me in the right direction RainyRat. – GAThrawn Dec 8 '09 at 11:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.