
我試圖讓 cmd 僅從命令輸出複製一組特定的字元。我已經能夠選擇該短語所在的行,但從那裡我迷失了。這是到目前為止我的命令。
ipconfig | findstr /i "ipv4"
相信你對ipconfig
命令和findstr
命令都很熟悉。基本上我是隔離特定電腦的 IPv4 位址。這就是上面的命令。
IPv4 Address. . . . . . . . . . . : 192.168.1.75
我想隔離“192.168.1”。並將其保存到變數中以便稍後在命令中使用。假設我設定了「192.168.1」。到 變數a
.
我希望運行的下一個命令掃描從 192.168.1.1 到 192.168.1.254 的所有 IP 位址並保存正在使用的位址。因為這個程式很快就會在「192.168.1」不同位置的不同電腦上運作。會有所不同,我希望隔離 cmd 放入其位置的任何內容。所以前面提到的變數A可以是但不限於 192.168.10.、10.10.10.、甚至 1.1.1。視情況而定。這是我將使用的程式碼。
FOR /L %i IN (1,1,254) DO ping -n 1 (the 'a' variable)%i | FIND /i "bytes=">>c:\ipaddresses.txt
或看看變數的樣子是否有幫助。
FOR /L %i IN (1,1,254) DO ping -n 1 192.168.1.%i | FIND /i "bytes=">>c:\ipaddresses.txt
我使用的是 64 位元 Windows 10 Pro 機器。
答案1
我想隔離“192.168.1”。並將其保存到變數中
使用以下批次檔 (test.cmd):
@echo off
setlocal
setlocal enabledelayedexpansion
rem throw away everything except the IPv4 address line
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "ipv4"`) do (
rem we have for example "IPv4 Address. . . . . . . . . . . : 192.168.42.78"
rem split on : and get 2nd token
for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
rem we have " 192.168.42.78"
rem split on . and get 4 tokens (octets)
for /f "tokens=1-4 delims=." %%c in ("%%b") do (
set _o1=%%c
set _o2=%%d
set _o3=%%e
set _o4=%%f
rem strip leading space from first octet
set _3octet=!_o1:~1!.!_o2!.!_o3!.
echo !_3octet!
)
)
)
rem add additional commands here
endlocal
筆記:
- 你想要的值保存在
_3octet
- 刪除
echo
用於調試的 - 替換
rem add additional commands here
為您的“網絡 ping”
範例用法和輸出:
F:\test>ipconfig | findstr /i "ipv4"
IPv4 Address. . . . . . . . . . . : 192.168.42.78
F:\test>test
192.168.42.
進一步閱讀
答案2
這適用於我在多台電腦上:
for /F "tokens=14" %A in ('"ipconfig | findstr IPv4"') do echo %A
答案3
嘗試這樣的事情。 “ipconfig /all > network_info.txt”只是為程式建立一個txt文件
ipconfig /all > network_info.txt
type network_info.txt | findstr /v Stuff | findstr /v Etc > whatyouwant.txt
set /p Build=<whatyouwant.txt
這個選項非常耗時,但非常簡單。你必須繼續做
| findstr /v something
並將該詞替換為您想要的內容。您必須決定如何從不同的行中刪除某些單字,但如果您想要簡單的話,這會起作用。我在輸出上使用它來刪除我不想要的垃圾的命令。理想情況下,您會將輸出放入 txt 中,並且它會讀取第一行,因此您只有 txt 的一行。希望我幫助或幫助了其他需要這個答案的人。它很複雜,但你也可以在 txt 中得到答案,如果這是一個加號的話
答案4
將 IP 位址指派給連續編號的環境變數(IP1、IP2)。對於具有多個網路適配器的系統。
@echo off
setlocal enabledelayedexpansion
set _count=1
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "ipv4"`) do (
for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
for /f "tokens=*" %%c IN ('echo %%b') do (set IP!_count!=%%c & echo IP!_count!=%%c & set /a _count+= 1)
)
)
set _count=
call :haltAndStore 2> nul
REM kludge: Forces batch processor to abort causing side-effect of persisting env vars.
:haltAndStore
()