Reputation: 1
I am trying to use the variables from the set command in dos, namely the %computername% to set a static IP address for a machine or two. I am a bit crap at writing code, so I have broken it down into simple steps, but don't know how to code it in dos, or perhaps powershell even, and would appreciate some help/guidance.
:end exit
I can get the netsh command to set the ip, if i use a variable %1 on the last octet of the IP address, for example setip.bat 11 so I know I can pass a variable, but I am unable to pull the variable from an echo statement
echo %computername% outputs PC201, but I dont know how to get this name decide what IP to give it, from a list perhaps of PC names and IPs I want to assign
Upvotes: 0
Views: 253
Reputation: 1211
I assume you want a PC/IP list. For the example I generate one:
for /l %i in (1,1,5) do @echo PC20%i,192.168.110.10%i>>"PC-IP List.csv"
Check the content:
type "PC-IP List.csv"
PC201,192.168.110.101
PC202,192.168.110.102
PC203,192.168.110.103
PC204,192.168.110.104
PC205,192.168.110.105
Assign the IP: (for safty here I only echo the command instead to execute it. Remove the "echo" for real usage)
for /f "usebackq tokens=1,2 delims=," %a in ("PC-IP List.csv") do @if "%a" == "%COMPUTERNAME%" (echo netsh interface ipv4 set address name -"Ethernet0" static %b 192.168.100.254)
tokens=1,2
tells to use item 1 and 2 from the list.
delims=,
tells the items are separated by a ,
%a
says, the first item will be stored in %a the second item will be stored in the alphabeticaly next name %b
usebackq
switches to the newer syntax within the brackets after the "in", so filenames with spaces can be used (and more).
("File Name")
Used like this (or without double quotes) the file content will be evaluated (influenced by 'usebackq').
When using this within a batch, you have to double the %a => %%a (the shell "eats" one of them) Sightly extended the batch can look like this:
@echo off
for /f "usebackq tokens=1,2 delims=," %%a in (%1) do (
@if /i "%%a" == "%COMPUTERNAME%" (
echo Found: %%a - Assigning IP %%b;
echo netsh interface ipv4 set address name -"Ethernet0" static %%b 192.168.100.254
)
)
Edit: Extended the if
clause in the batch script to ignore the case of %COMPUTERNAME% at comparison.
This batch takes the filename of the CSV-List as the first parameter:
script.bat "PC-IP List.csv"
Please note:
You can get more details at the buildin help by typing for /?
and if /?
Upvotes: 0