屏蔽多个主机的Windows批处理文件(使用列表)

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

我想在hosts文件中添加多行不存在的内容。我的代码工作得很好,但我想为一个有30个条目的列表做这件事,这就是我不知道如何处理的地方。我想过一个列表和一个for-loop,但我不知道如何处理。

@ECHO OFF

ECHO Checking administrator right.

OPENFILES >NUL 2>&1
IF %ERRORLEVEL% EQU 0 (

    ECHO Administrator right detected.
    ECHO.
    ECHO Hosts file : %WINDIR%\system32\drivers\etc\hosts
    ECHO.

    SETLOCAL ENABLEDELAYEDEXPANSION

        SET BLOCKLINE=127.0.0.1 example.com
        ECHO Checking : !BLOCKLINE!
        FIND /C /I "!BLOCKLINE!" "%WINDIR%\system32\drivers\etc\hosts" >NUL 2>NUL
        IF !ERRORLEVEL! NEQ 0 (
            ECHO Line not found, adding to the hosts file.
            ECHO !BLOCKLINE!>>%WINDIR%\system32\drivers\etc\hosts
        ) ELSE (
            ECHO Line found.
        )
        ECHO.

    ENDLOCAL

    ECHO Patching is completed.
    ECHO Check hosts file if you want to see the result.
    ECHO.

) ELSE (

    ECHO Administrator right not detected.
    ECHO You need admin right to use this hosts patch!
    ECHO.

)

PAUSE
windows batch-file
1个回答
2
投票

一个基本的for循环就足够了.在循环集中定义要测试的行。

For %%L in (
    "127.0.0.1 example1"
    "127.0.0.30 example30"
) Do (
    ECHO Checking : %%~L
    FIND /C /I "%%~L" "%WINDIR%\system32\drivers\etc\hosts" >NUL 2>NUL
    IF !ERRORLEVEL! NEQ 0 (
        ECHO Line not found, adding to the hosts file.
        >>"%WINDIR%\system32\drivers\etc\hosts" ECHO %%~L
    ) ELSE (
        ECHO Line found.
    )
)
© www.soinside.com 2019 - 2024. All rights reserved.