I am writing a batch file to do some operations on remote computers in my building. They are all named with the same prefix, but the number at the end changes (01–65). I tried to follow an online tutorial for creating a batch file loop based on numbers, and came up with this:
FOR /l %%N in (1,1,65) do (
set HOSTNAMETOUSE=prefix-%%N
ECHO %HOSTNAMETOUSE%
)
This works great after it hits 10, as then it's two digits. What I need is for the numbers 1-9
to appear as 01-09
, as that matches our naming schema. Essentially, I need the single-digit of a leading zero for the first 9 iterations. How can I accomplish this with Windows Batch Files?
Your posted code cannot possibly work because %HOSTNAMETOUSE%
is expanded when the statement is parsed, and the entire parenthesized block is parsed in one pass, before the loop is executed. So the expanded value is constant for all iterations.
You must use delayed expansion to get the value upon execution time.
@echo off
setlocal enableDelayedExpansion
FOR /l %%N in (1,1,65) do (
set HOSTNAMETOUSE=prefix-%%N
ECHO !HOSTNAMETOUSE!
)
Now to prefix with 0 as needed.
Since you never need more than a single 0, you could use an IF statement.
@echo off
setlocal enableDelayedExpansion
FOR /l %%N in (1,1,65) do (
if %%N lss 10 (set HOSTNAMETOUSE=prefix-0%%N) else set HOSTNAMETOUSE=prefix-%%N
ECHO !HOSTNAMETOUSE!
)
But that is not convenient if your number width is more than 2 digits. A more general solution is to add a string of n zeros with your desired length, and then use a substring operation to keep the n right most digits.
@echo off
setlocal enableDelayedExpansion
FOR /l %%N in (1,1,65) do (
set "n=00%%N"
set "HOSTNAMETOUSE=!n:~-2!
ECHO !HOSTNAMETOUSE!
)
You can easily extend this solution to virtually any number of leading zeros.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다