如何在批处理文件中请求管理员访问权限 [英] How to request Administrator access inside a batch file

查看:37
本文介绍了如何在批处理文件中请求管理员访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的用户编写一个批处理文件,以便使用 UAC 从他们的 Vista 机器上运行.该文件正在重写其主机文件,因此需要以管理员权限运行.我需要能够向他们发送一封电子邮件,其中包含指向 .bat 文件的链接.所需的行为是,当他们右键单击文件并说打开"时,他们将获得使屏幕变暗并强制他们回答是否要授予应用程序以管理员身份运行的权限的那些 UAC 对话框之一.相反,他们只是在命令行窗口中看到拒绝访问".

I am trying to write a batch file for my users to run from their Vista machines with UAC. The file is re-writing their hosts file, so it needs to be run with Administrator permissions. I need to be able to send them an email with a link to the .bat file. The desired behavior is that when they right-click on the file and say Open, they will get one of those UAC dialogs that makes the screen go dark and forces them to answer whether they want to give the application permission to run as administrator. Instead, they are just seeing "Access denied" on the command line window.

这有可能以不同的方式做吗?

Is this possible to do differently?

推荐答案

这个脚本可以解决问题!只需将其粘贴到 bat 文件的顶部即可.如果要查看脚本的输出,请在批处理文件底部添加暂停"命令.

This script does the trick! Just paste it into the top of your bat file. If you want to review the output of your script, add a "pause" command at the bottom of your batch file.

更新:这个脚本现在略有编辑以支持命令行参数和 64 位操作系统.

UPDATE: This script is now slightly edited to support command line arguments and a 64 bit OS.

谢谢 Eneerge @ https://sites.google.com/site/eneerge/脚本/batchgotadmin

Thank you Eneerge @ https://sites.google.com/site/eneerge/scripts/batchgotadmin

@echo off

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
    IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
>nul 2>&1 "%SYSTEMROOT%SysWOW64cacls.exe" "%SYSTEMROOT%SysWOW64configsystem"
) ELSE (
>nul 2>&1 "%SYSTEMROOT%system32cacls.exe" "%SYSTEMROOT%system32configsystem"
)

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"
:--------------------------------------    
    <YOUR BATCH SCRIPT HERE>

这篇关于如何在批处理文件中请求管理员访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆