要编辑主机文件的批处理文件连续运行而不停止


@Echo off
:: Check for permissions
>nul 2>&1 "%SYSTEMROOT%system32cacls.exe" "%SYSTEMROOT%system32configsystem"
:: 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"
Echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%getadmin.vbs"
"%temp%getadmin.vbs"
Exit /B
:gotAdmin
if exist "%temp%getadmin.vbs" ( Del "%temp%getadmin.vbs" )
Pushd "%CD%"
CD /D "%~dp0"
C:WindowsSystem32notepad.exe C:WindowsSystem32driversetchosts

我正在使用上面的批处理文件编辑主机文件。在windows 7中,默认情况下不会出现UAC提示符。所以我用了这个。但是,当用户没有管理员权限来编辑主机文件时,它会持续运行if循环,并且需要注销或重新启动系统才能停止该进程。

所以谁能建议任何更改批处理文件,这样它就会运行一次或两次,如果没有得到管理权限,那么就退出。

谢谢Sibasundar

向脚本添加一个参数,让它知道它是否被自调用。如果脚本是自调用的,并且没有admin权限,则退出。

@echo off
setlocal EnableExtensions
set "VBS=%Temp%getadmin.vbs"
:: Check for permissions
>nul 2>&1 "%SystemRoot%System32cacls.exe" "%SystemRoot%System32configsystem"
if "%ErrorLevel%"=="0" goto gotAdmin
if /i "%~1"=="Self" exit /b 1
goto UACPrompt

:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%VBS%"
echo UAC.ShellExecute "%~s0", "Self %*", "", "runas", 1 >> "%VBS%"
echo Requesting administrative privileges...
"%VBS%"
exit /b 1

:gotAdmin
shift
if exist "%VBS%" del "%VBS%"
pushd "%CD%"
cd /d "%~dp0"
"%SystemRoot%System32notepad.exe" "%SystemRoot%System32driversetchosts"
popd
endlocal

更新:

@echo off
setlocal EnableExtensions
set "ExitCode=0"
set "VBS=%Temp%getadmin.vbs"
:: Check for permissions
>nul 2>&1 "%SystemRoot%System32cacls.exe" "%SystemRoot%System32configsystem"
if "%ErrorLevel%"=="0" goto gotAdmin
if /i "%~1"=="Self" goto ElevateFail
goto UACPrompt

:ElevateFail
set "ExitCode=1"
echo Error: Administrator privileges are required.
pause>nul
goto End

:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%VBS%"
echo UAC.ShellExecute "%~s0", "Self %*", "", "runas", 1 >> "%VBS%"
echo Requesting administrative privileges...
"%VBS%"
goto End

:gotAdmin
shift
if exist "%VBS%" del "%VBS%"
pushd "%CD%"
cd /d "%~dp0"
"%SystemRoot%System32notepad.exe" "%SystemRoot%System32driversetchosts"
popd

:End
endlocal & exit /b %ExitCode%

在代码末尾使用:PAUSE

@Echo off
:: Check for permissions
>nul 2>&1 "%SYSTEMROOT%system32cacls.exe" "%SYSTEMROOT%system32configsystem"
:: 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"
Echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%getadmin.vbs"
"%temp%getadmin.vbs"
Exit /B
:gotAdmin
if exist "%temp%getadmin.vbs" ( Del "%temp%getadmin.vbs" )
Pushd "%CD%"
CD /D "%~dp0"
C:WindowsSystem32notepad.exe C:WindowsSystem32driversetchosts
:PAUSE

最新更新