這裏是T-Diddy發佈的批處理代碼的改進版,適用於英語和德語的Windows。
@echo off
rem Set primary and alternate DNS for IPv4.
setlocal
set "SITEID=020"
rem The next line removes leading zeros to define the third octet of the
rem IPv4 address always correct. There are implementations on IP address
rem parsing routines on Windows (for example command ping) and Linux which
rem interpret integer numbers with a leading 0 as octal number and not as
rem decimal number according to C standard. The number 020 would be set
rem unexpected as decimal number 16 instead of 20.
for /F "tokens=* delims=0" %%A in ("%SITEID%") do set DROPZERO=%%A
rem Get first ethernet adapter name output by command IPCONFIG filtered
rem by command FINDSTR with a case-insensitive regular expression search.
rem "Ethernet adapter " is output left to the name of the adapter on English
rem Windows. But on German Windows "Ethernetadapter" is the right word. This
rem is the reason for the regular expression with an optional space between
rem "ethernet" and "adpater".
set "AdapterName="
for /F "tokens=* delims=:" %%A in ('%SystemRoot%\System32\ipconfig.exe ^| %SystemRoot%\System32\findstr.exe /I /R "ethernet.*adapter"') do (
set "AdapterName=%%A"
goto SetAddress
)
rem No ethernet adapter found, exit batch job.
endlocal
goto :EOF
:SetAddress
rem Remove everything from beginning of string to first occurrence of
rem the string "adapter " to remove "Ethernet adapter " respectively
rem on German Windows "Ethernetadapter".
set "AdapterName=%AdapterName:*adapter =%"
rem Remove the colon from the end of the adapter name.
set "AdapterName=%AdapterName:~0,-1%"
echo Ethernet adapter found: %AdapterName%
echo Setting static IP information ...
set IpAddress=10.102.%DROPZERO%.105
set DefaultGate=10.102.%DROPZERO%.1
set SubNetMask=255.255.255.0
%SystemRoot%\System32\netsh.exe interface ip set address "%adapterName%" static %IpAddress% %SubNetMask% %DefaultGate% ^1>output_net.txt
%SystemRoot%\System32\netsh.exe interface ip set dns name="%adapterName%" static 10.98.1.26 primary>>output_net.txt
%SystemRoot%\System32\netsh.exe interface ip add dns name="%adapterName%" 10.98.1.48 index=^2>>output_net.txt
endlocal
我在這裏看不到在Windows XP中的一個問題上使用
set "AdapterName=%AdapterName:~0,-1%"
但在for
循環命令findstr
是用來代替find
。在設置適配器名稱時使用雙引號,以避免錯誤地將尾隨空格附加到適配器的名稱上。這可能是重要的區別。
供大家閱讀這個答案的一般注意事項:
決不1個或2前導零進入4個字節的IPv4地址。這很容易導致被解釋爲八進制數,這絕對不是人們所期望的。
你不相信。嘗試一下在Linux或Windows例如在運行命令
ping 192.168.050.020
你有沒有預料寫在輸出平與192.168.40.16執行?
也許'ipconfig'輸出的格式不同於Windows 7到XP。看看'IPCONFIG^|的輸出在Windows 7中查找/ I「ETHERNET ADAPTER」,然後在XP中查找。如果格式不同,那麼for循環可能不會正確設置'adapterName'。 – unclemeat
我按照你的建議分解了它,並且正確設置了adaptername。 –
用'echo netsh'替換你的'netsh'調用,看看這些命令是否是你認爲的那些。 – Mark