如何使用管理员打开文件,使用bat编辑和保存

时间:2017-06-19 13:06:48

标签: windows batch-file cmd

如何创建bat文件以便与管理员一起打开特定文件(主机),编辑并保存?

我试过了,但它没有工作:

echo C:\Windows\System32\drivers\etc\hosts >> 192.168.100.9       dev.rw1.local
echo C:\Windows\System32\drivers\etc\hosts >> 192.168.100.10       wiki.rw1.local

我也试过直接在CMD和CMD中使用它作为管理员并且没有工作

1 个答案:

答案 0 :(得分:1)

您可以试试这个批处理文件:

@echo off
Color 9A & Mode con cols=83 lines=5
Title %~n0 Add some lines on hosts files
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM  --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO                      **************************************
ECHO                       Running Admin shell... Please wait...
ECHO                      **************************************

    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
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::

set "hostspath=%windir%\System32\drivers\etc\hosts"

FIND /C /I "dev.rw1.local" "%hostspath%" >nul
FIND /C /I "wiki.rw1.local" "%hostspath%" >nul


IF "%ERRORLEVEL%" NEQ "0" (
    Attrib -R %hostspath%
    (
        echo(
        echo ###############################################
        echo # Lines added by "%username%" #
        echo 192.168.100.9       dev.rw1.local
        echo 192.168.100.10      wiki.rw1.local
        echo ###############################################
    )>> "%hostspath%"
) 

Attrib +R "%hostspath%"