Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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:

echo %COMPUTERNAME% | FIND /I "UKD"

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

FOR %%A IN (UKD UKL USD) DO echo %COMPUTERNAME% | FIND /C /I "%%A"

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

1 Answer 1

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
2  
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

 
discard

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.