2016-01-13 54 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 –