bat file only by computer name

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
albayco
Posts: 1
Joined: 25 Mar 2021 00:49

bat file only by computer name

#1 Post by albayco » 25 Mar 2021 00:55

hi, How to run command in bat script only if computer name start with XXX ? like 01 / 02 / 03

The bat file I made is as follows, but the file does not work and closes. I wonder where am I going wrong.

Code: Select all

@echo off

IF %COMPUTERNAME%== "01" (
    start_1.bat
) ELSE IF %COMPUTERNAME%== "02" (
    start_2.bat
) ELSE IF %COMPUTERNAME%== "03" (
    start_3.bat
) ELSE (
echo.
echo empty.
)

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: bat file only by computer name

#2 Post by Squashman » 25 Mar 2021 08:02

I see part of your problem was solved on StackOverFlow but nobody gave you direction on substrings of variables. This is explained in the help file for the `SET` command.

Code: Select all

May also specify substrings for an expansion.

    %PATH:~10,5%

would expand the PATH environment variable, and then use only the 5
characters that begin at the 11th (offset 10) character of the expanded
result.  If the length is not specified, then it defaults to the
remainder of the variable value.  If either number (offset or length) is
negative, then the number used is the length of the environment variable
value added to the offset or length specified.

    %PATH:~-10%

would extract the last 10 characters of the PATH variable.

    %PATH:~0,-2%

would extract all but the last 2 characters of the PATH variable.

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: bat file only by computer name

#3 Post by Aacini » 25 Mar 2021 17:42

I suggest you to not use a series of IF's at all, but directly take the value you want to start the desired batch file.

Perhaps this idea can be comprehended in a simpler way if you review this code:

Code: Select all

rem Add the value of I (that can only be 1, 2 or 3) to SUM variable:

IF %I% == 1 (
   SET /A SUM = SUM + 1
) ELSE IF %I% == 2 (
   SET /A SUM = SUM + 2
) ELSE IF %I% == 3 (
   SET /A SUM = SUM + 3
) ELSE (
   echo Bad number
)
It is simpler this way, isn't it?

Code: Select all

SET /A SUM = SUM + %I%
You may do the same this way:

Code: Select all

start_%COMPUTERNAME:~0,2%.bat
... and name your Batch files as start_01.bat, start_02.bat and start_03.bat, and even create start_.bat file that just display "empty."

Antonio

Post Reply