for循环在CMD提示符下工作但不在批处理文件中

时间:2015-11-13 23:40:56

标签: batch-file for-loop cmd

我有这个代码在我的CMD promt上运行(有一个%而不是%%)但是当我通过.bat文件执行它时它不工作。

for /f "tokens=5 delims=: " %%G in ('netsh interface IPv4 show dnsserver "Ethernet 2" ^| findstr /C:"Servidores DNS configurados estáticamente"') DO (Echo %%G)

我试图做一个.bat,将我的主DNS和辅助DNS换成另外两个。我正在尝试这样的事情:

@echo off  
cls  
color A
cls

SET DNS1=46.101.36.120
SET DNS2=46.101.149.135
SET DNSGoogle1=8.8.8.8
SET DNSGoogle2=8.8.4.4
SET NAME=Ethernet 2


for /f "tokens=5 delims=: " %%G in ('netsh interface IPv4 show dnsserver "%NAME%" ^| findstr /C:"Servidores DNS configurados estáticamente"') DO IF %DNSGoogle1%==%%G (goto netflixDNS) ELSE (goto googleDNS)


:netflixDNS
echo "Netflix DNS"
netsh interface ipv4 delete dnsserver "%NAME%" all
netsh interface ip set dnsservers "%NAME%" static %DNS1%
netsh interface ip add dnsservers "%NAME%" %DNS2% index=2
ipconfig /flushdns
PAUSE
EXIT

:googleDNS
echo "Google DNS"
netsh interface ipv4 delete dnsserver "%NAME%" all
netsh interface ip set dnsservers "%NAME%" static %DNSGoogle1%
netsh interface ip add dnsservers "%NAME%" %DNSGoogle2% index=2
ipconfig /flushdns
PAUSE
EXIT

由于某种原因,我FOR无法正常工作......

1 个答案:

答案 0 :(得分:3)

虽然wOxxOm的评论已经解决,但这个问题需要一些解释:明目张胆的mojibake案例。要避免这种类型的mojibake,请在保存的同一代码页下运行批处理脚本:如果以ANSI编码(CP1252)保存,则假定notepad

证明:

请不要将下一个代码段插入批处理脚本。 复制&在打开的命令行窗口中粘贴

chcp 850>NUL
echo áéíóúüýñäëêöã  850>ew-850.txt
chcp 1252>NUL
echo áéíóúüýñäëêöã 1252>ew1252.txt
for %G in (437 850 1252) do @chcp %G&>NUL timeout /T 1 &findstr "^" "ew*.txt"

<强>输出

==> chcp 850>NUL

==> echo áéíóúüýñäëêöã  850>ew-850.txt

==> chcp 1252>NUL

==> echo áéíóúüýñäëêöã 1252>ew1252.txt

==> for %G in (437 850 1252) do @chcp %G&>NUL timeout /T 1 &findstr "^" "ew*.txt"
Active code page: 437
ew-850.txt:áéíóúü∞ñäëêö╞  850
ew1252.txt:ßΘφ≤·ⁿ²±ΣδΩ÷π 1252
Active code page: 850
ew-850.txt:áéíóúüýñäëêöã  850
ew1252.txt:ßÚݾ·³²±õÙÛ÷Ò 1252
Active code page: 1252
ew-850.txt: ‚¡¢£ì¤„‰ˆ”Æ  850
ew1252.txt:áéíóúüýñäëêöã 1252

==>

Czech and Slovak accented letters和中欧编码(代码页CP852CP1250)的(不完整分类)的另一个示例:

chcp 852>NUL
echo áéíóúůýňěščřž  852>ee-852.txt
chcp 1250>NUL
echo áéíóúůýňěščřž 1250>ee1250.txt
for %G in (437 852 1250) do @chcp %G&>NUL timeout /T 1 &findstr "^" "ee*.txt"

修改:另一个额外的说明性示例(复制并粘贴到cmd窗口中)。

ECHO OFF
chcp 850>NUL
echo echo %~0 [áéíóúüýñäëêöã] 850>ew-850.bat
chcp 1252>NUL
echo echo %~0 [áéíóúüýñäëêöã]1252>ew1252.bat
chcp 850>NUL
ew-850.bat
ew1252.bat
chcp 1252>NUL
ew-850.bat
ew1252.bat
ECHO ON

<强>输出

==> ECHO OFF
chcp 850>NUL
echo echo %~0 [áéíóúüýñäëêöã] 850>ew-850.bat
chcp 1252>NUL
echo echo %~0 [áéíóúüýñäëêöã]1252>ew1252.bat
chcp 850>NUL
ew-850.bat
ew-850.bat [áéíóúüýñäëêöã] 850
ew1252.bat
ew1252.bat [ßÚݾ·³²±õÙÛ÷Ò]1252
chcp 1252>NUL
ew-850.bat
ew-850.bat [ ‚¡¢£ì¤„‰ˆ”Æ] 850
ew1252.bat
ew1252.bat [áéíóúüýñäëêöã]1252
ECHO ON

==>