2016-01-13 43 views
0

我希望能够有一个2选项批处理文件,该文件可以写入四行文字,并且还可以删除这些特定行而不擦除其中的其他行主机文件。我有一个脚本,我在这里找到:Windows Batch: How to add Host-Entries?,我编辑为我自己的用途,但我很难在如何去解决这个问题,因为我很新,编写批处理文件。想你们可以帮助我吗?制作批处理文件以向主机添加/删除特定行文件

@echo off 

REM ...fluff removed...  

:ACCEPTED 
setlocal enabledelayedexpansion 
::Create your list of host domains 
set LIST=(osu.ppy.sh a.ppy.sh c.ppy.sh c1.ppy.sh) 
::Set the ip of the domains you set in the list above 
set osu.ppy.sh=178.62.57.37 
set a.ppy.sh=178.62.57.37 
set c.ppy.sh=178.62.57.37 
set c1.ppy.sh=178.62.57.37 
:: deletes the parentheses from LIST 
set _list=%LIST:~1,-1% 
::ECHO %WINDIR%\System32\drivers\etc\hosts > tmp.txt 
for %%G in (%_list%) do (
    set _name=%%G 
    set _value=!%%G! 
    SET NEWLINE=^& echo. 
    ECHO Carrying out requested modifications to your HOSTS file 
    ::strip out this specific line and store in tmp file 
    type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_name! > tmp.txt 
    ::re-add the line to it 
    ECHO %NEWLINE%^!_value! !_name!>>tmp.txt 
    ::overwrite host file 
    copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts 
    del tmp.txt 
) 
ipconfig /flushdns 
ECHO. 
ECHO. 
ECHO Finished, you may close this window now. 
GOTO END 

:END 
EXIT 

回答

0
@ECHO OFF 
SETLOCAL ENABLEDELAYEDEXPANSION 

:ACCEPTED 
setlocal enabledelayedexpansion 
SET "filename1=%WINDIR%\System32\drivers\etc\hosts" 
SET "filename1=q34775003.txt" 
::Create your list of host domains 
set LIST=(osu.ppy.sh a.ppy.sh c.ppy.sh c1.ppy.sh) 
::Set the ip of the domains you set in the list above 
set osu.ppy.sh=178.62.57.37 
set a.ppy.sh=178.62.57.37 
set c.ppy.sh=178.62.57.37 
set c1.ppy.sh=178.62.57.37 

ECHO Carrying out requested modifications to your HOSTS file 
:: remove existing names from hosts file 

findstr /v /e "%LIST:~1,-1%" "%filename1%"> tmp.txt 

:: Add new list 
for %%G in %list% do (
rem set _name=%%G 
rem set _value=!%%G! 
    ECHO !%%G! %%G>>tmp.txt 
) 
::overwrite host file 
move tmp.txt %filename1% >nul 
) 

在一个块内声明(a parenthesised series of statements)REM语句,而不是破碎的标签备注形式(:: comment)应该被使用,因为标签终止块,混淆cmd

这是一个完整的修订版,因为我弄错了解释原始批处理的内容。

它的目的,这取代了常规:ACCEPTED - 你需要重新插入ipconfig命令

filename1被设置为真实filelocation,然后进行测试的测试文件的位置。您需要删除多余的设置。

首先,删除现有的名称条目,并用余数创建temp.txt。要匹配(因此被删除)该名称必须匹配该行的末尾,因此a.ppy.sh将被删除,但a.ppy.shx将被保留。

接下来,新的条目附加到temp.txt

最后,move替换原来的文件。

所有需要做的是测试用一个虚拟文件和证明的情况下,ipconfig...线附加在原有

最后,

+0

我该如何去实现这个脚本?它可以自行运行,因为即使在管理员中运行,它似乎也不会删除这些行。虽然我可能是错的,因为我真的不知道自己在做什么。我非常感谢你的帮助。 –

0

如果您打算编写或删除相同的四行,为什么不创建和维护两个文件(短和长版本)?然后根据你想要做的事情复制相应的文件?

例子:

pushd %systemroot%\system32\drivers\etc 
choice /C:SL "Choose S for short or L for long." 
IF errorlevel 2 goto long 
IF errorlevel 1 goto short 

:long 
copy hosts.long hosts 
goto end 

:short 
copy hosts.short hosts 
goto end 

:end 
popd 

就个人而言,我会使用PowerShell的,但你没有问批处理文件。

+0

无论是或作品,我只需要能够分配这很容易没有太多的设置。我正在使用类似于你之前建议的东西http://pastebin.com/jNFcmULL –

相关问题