Windows – Batch file match start of machine name

batch-filewindows

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?

Best Answer

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.