使用 txt 文件添加主机条目的脚本

问题描述 投票:0回答:1

我需要一个 cmd scritp 将多行从 txt 文件添加到主机文件。

我在this中找到了Tony

的脚本
@echo off
TITLE Modifying your HOSTS file
ECHO.

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged.
ECHO Finished.
GOTO END


:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
for /F "tokens=1,2 delims=  " %%A in (%WINDIR%\System32\drivers\etc\storedhosts.txt) do (
    SET _host=%%B
    SET _ip=%%A
    SET NEWLINE=^& echo.
    ECHO Adding !_ip!       !_host!
    REM REM ::strip out this specific line and store in tmp file
    type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_host! > tmp.txt
    REM REM ::re-add the line to it
    ECHO %NEWLINE%^!_ip!        !_host! >> tmp.txt
    REM ::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
ECHO.
PAUSE
EXIT

示例“storedhosts.txt”(制表符分隔)

127.0.0.1   mysite.com
168.1.64.2  yoursite.com
192.1.0.1   internalsite.com

但它对我不起作用,它删除所有 HOSTS 文件并只写入最后一个条目。

当脚本启动时,每个 ip 都会出现此错误

FIND: Parameter format not correct" and "FINDSTR: Write error" with Pipes
有人可以帮我修改这个脚本吗?谢谢你

batch-file hosts
1个回答
0
投票

我没有对此进行测试,但

copy /?
揭示了以下内容:

要追加文件,请指定单个文件作为目标,但指定多个文件 对于源(使用通配符或 file1+file2+file3 格式)。

所以,我只需替换这个命令:

copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts

作者:

copy /b/v/y tmp.txt+%WINDIR%\System32\drivers\etc\hosts %WINDIR%\System32\drivers\etc\hosts
© www.soinside.com 2019 - 2024. All rights reserved.