Reputation:
Okey-dokey. So you know the net view command? I basicly want each pc in that list to be assigned to its own variable. For example, if the output of net view was:
Server Name Remark
-------------------------------------------------------------------------------
\\CARLY-PC
\\COLTON-WIN8
The command completed successfully.
I want
%a% = CARLY-PC
%b% = COLTON-WIN8
for however many items are listed.
Unfortunately I have no idea how to do this. I don't understand the FOR command, as i think that this is what you would have to use.
Upvotes: 0
Views: 849
Reputation: 67236
The FOR /F command is used to execute another command and get its output. For example:
for /F %%a in ('net view') do echo %%a
Execute "net view" and get the first token separated by space (default values) of each line, so the output is:
Server
-------------------------------------------------------------------------------
\\CARLY-PC
\\COLTON-WIN8
The
Now we may select server names if the first two characters are "\". The tricky part is to generate different letters for the variables, but we may define a string with those letters and select the appropriate one with an index variable:
@echo off
setlocal EnableDelayedExpansion
set vars=abcdefghijklmnopqrstuvwxyz
set i=0
for /F %%a in ('net view') do (
set line=%%a
if "!line:~0,2!" equ "\\" (
for %%i in (!i!) do set !vars:~%%i,1!=!line:~2!
set /A i+=1
)
)
EDIT: New solution as reply to the comment
Your requirement of store each value in variables with different names is unusual, because this method forces to write different program lines in order to process each variable. A much simpler method is to use an array and select the desired element via an index:
@echo off
color a
title Local IP address finder
:start
cls
setlocal EnableDelayedExpansion
set i=0
for /F %%a in ('net view') do (
set line=%%a
if "!line:~0,2!" equ "\\" (
set /A i+=1
echo [!i!] !line:~2!
set comp[!i!]=!line:~2!
)
)
echo.
echo.
echo Choose a computer.
choice /c 12345678 >nul
set name=!comp[%errorlevel%]!
cls
for /f "tokens=1,2 delims=[]" %%A in ('ping -4 %name% ^| find "Pinging"') do set ipaddress=%%B
if "%name%"=="" goto start
echo The IP address of %name% is %ipaddress%
echo.
echo.
echo %ipaddress% | clip
echo. %ipaddress% copyied to clipboard.
echo.
echo Press any key.
pause >nul
goto start
You may read a description of array management in Batch files here: Arrays, linked lists and other data structures in cmd.exe (batch) script
PS - Your code have a bug in this line, the + operator is missed:
set /A i=1
Upvotes: 1