0

I have this script for naming a machine. It is for an automatic rename after I successfully re-imaged a machine. To save time when doing 40 or 50 at a time.

SETLOCAL ENABLEDELAYEDEXPANSION
@ECHO OFF
SET count=1
SET campus=JOB

FOR /F "tokens=* USEBACKQ" %%F IN (`wmic bios get serialnumber`) DO ( 
SET serialnumber!count!=%%F
SET /a count=!count!+1
)

SET pcname=%campus%-%serialnumber2%

ENDLOCAL

WMIC computersystem where caption=%computername% rename %pcname%

pause

I have several different campuses and with either a 3 or 4 character name scheme and using the serial number of the device. I was wondering if there was a way to find out if the %pcname% is less than or equal to 15 characters, if not, then cut off the last digits to equal 15 characters? Since Microsoft only allows 15 characters for a computer name, then this script should account for it. In theory.

Harley Frank
  • 149
  • 2
  • 11

2 Answers2

1

Just :

set pcname=%pcname:~0,15%

If its longer it will be cutted if not it will stay as it is

In your code :

SETLOCAL ENABLEDELAYEDEXPANSION
@ECHO OFF
SET count=1
SET campus=JOB

FOR /F "tokens=* USEBACKQ" %%F IN (`wmic bios get serialnumber`) DO ( 
SET serialnumber!count!=%%F
SET /a count=!count!+1
)

SET pcname=%campus%-%serialnumber2%

::
SET pcname=%pcname:~0,15%
SET pcname=%pcname: =%
::


WMIC computersystem where caption=%computername% rename %pcname%

pause

That should do the trick !

SachaDee
  • 9,245
  • 3
  • 23
  • 33
1
SET pcname=%campus%-%serialnumber2%
set pcname=%pcname:~0,15%
REM ENDLOCAL

WMIC computersystem where caption=%computername% rename %pcname%

The endlocal will end the local environment established by the preceding setlocal and discard any changes made to the environment since then (like - changing variables' contents, for instance...)

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • I have a question, should I remove the set local entirely? – Harley Frank Jun 22 '17 at 20:13
  • Absolutely not! (Although it's conventional to put it *after* the `@echo off`). The only way to invoke `delayedexpansion` ( which you need because you are altering `count` within a code block and using the altered value) is by using a `setlocal`. Also, using a `setlocal` ensures that the environment remains clean and is not cluttered by changes made to the environment by running batches. If it is omitted, the changes made persist, so you may "inherit" a variable set by a completely unrelated batch. – Magoo Jun 22 '17 at 20:21