如何在批处理文件中请求管理员访问权限

发布于 2024-08-14 17:42:32 字数 232 浏览 7 评论 0原文

我正在尝试为我的用户编写一个批处理文件,以便使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

剧终人散尽 2024-08-21 17:42:32

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

更新:此脚本现已稍微编辑以支持命令行参数和 64 位操作系统。

谢谢 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%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>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"
:--------------------------------------    
    <YOUR BATCH SCRIPT HERE>

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.

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

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%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
>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"
:--------------------------------------    
    <YOUR BATCH SCRIPT HERE>
一绘本一梦想 2024-08-21 17:42:32

这是我一直在使用的:

@echo off
if not "%1"=="am_admin" (
    powershell -Command "Start-Process -Verb RunAs -FilePath '%0' -ArgumentList 'am_admin'"
    exit /b
)

echo main code here
pause

注意:

  • -Verb RunAs 标志可启用管理提升。
  • 仅在 Windows 7 和 10 上进行了测试,您可能不得不搞乱引用
  • 暂时不支持传递参数,但您也许可以向 -ArgumentList 添加更多内容。请注意 -ArgumentList 接受单个字符串或字符串数​​组。

Here's what I've been using:

@echo off
if not "%1"=="am_admin" (
    powershell -Command "Start-Process -Verb RunAs -FilePath '%0' -ArgumentList 'am_admin'"
    exit /b
)

echo main code here
pause

Notes:

  • The -Verb RunAs flag of Start-Process is what enables the administrative elevation.
  • Only tested on windows 7 and 10, you might have to mess around with the quoting
  • Doesn't support passing along arguments for now, but you might be able to add more stuff to -ArgumentList. Note that -ArgumentList accepts either a single string or a string array.
你是我的挚爱i 2024-08-21 17:42:32

这是我的代码!它看起来很大,但主要是注释行(以 :: 开头的行)。

特点:

  • 完整参数转发

  • 不更改工作文件夹

  • 错误处理

  • 接受带括号的路径(%TEMP% 文件夹除外)

  • 支持 UNC 路径

  • 映射文件夹检查(如果管理员无法访问映射驱动器,则会向您发出警告)

  • 可以用作外部库(查看我在该主题中的帖子:https://stackoverflow.com/a/30417025/4932683)

  • 可以在代码中的任何地方需要时/如果需要时调用

只需将其附加到批处理文件的末尾,或将其另存为库(检查上面)

    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:RequestAdminElevation FilePath %* || goto:eof
:: 
:: By:   Cyberponk,     v1.6 - 05/05/2023 - Fixed crash when batch filename contained spaces
::          v1.5 - 10/06/2016 - Changed the admin rights test method from cacls to fltmc
::          v1.4 - 17/05/2016 - Added instructions for arguments with ! char
::          v1.3 - 01/08/2015 - Fixed not returning to original folder after elevation successful
::          v1.2 - 30/07/2015 - Added error message when running from mapped drive
::          v1.1 - 01/06/2015
:: 
:: Func: opens an admin elevation prompt. If elevated, runs everything after the function call, with elevated rights.
:: Returns: -1 if elevation was requested
::           0 if elevation was successful
::           1 if an error occured
:: 
:: USAGE:
:: If function is copied to a batch file:
::     call :RequestAdminElevation "%~dpf0" %* || goto:eof
::
:: If called as an external library (from a separate batch file):
::     set "_DeleteOnExit=0" on Options
::     (call :RequestAdminElevation "%~dpf0" %* || goto:eof) && CD /D %CD%
::
:: If called from inside another CALL, you must set "_ThisFile=%~dpf0" at the beginning of the file
::     call :RequestAdminElevation "%_ThisFile%" %* || goto:eof
::
:: If you need to use the ! char in the arguments, the calling must be done like this, and afterwards you must use %args% to get the correct arguments:
::      set "args=%* "
::      call :RequestAdminElevation .....   use one of the above but replace the %* with %args:!={a)%
::      set "args=%args:{a)=!%" 
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
setlocal ENABLEDELAYEDEXPANSION & set "_FilePath=%~1"
  if NOT EXIST "!_FilePath!" (echo/Read RequestAdminElevation usage information)
  :: UAC.ShellExecute only works with 8.3 filename, so use %~s1
  set "_FN=_%~ns1" & echo/%TEMP%| findstr /C:"(" >nul && (echo/ERROR: %%TEMP%% path can not contain parenthesis &pause &endlocal &fc;: 2>nul & goto:eof)
  :: Remove parenthesis from the temp filename
  set _FN=%_FN:(=%
  set _vbspath="%temp:~%\%_FN:)=%.vbs" & set "_batpath=%temp:~%\%_FN:)=%.bat"

  :: Test if we gave admin rights
  fltmc >nul 2>&1 || goto :_getElevation

  :: Elevation successful
  (if exist %_vbspath% ( del %_vbspath% )) & (if exist "%_batpath%" ( del "%_batpath%" )) 
  :: Set ERRORLEVEL 0, set original folder and exit
  endlocal & CD /D "%~dp1" & ver >nul & goto:eof

  :_getElevation
  echo/Requesting elevation...
  :: Try to create %_vbspath% file. If failed, exit with ERRORLEVEL 1
  echo/Set UAC = CreateObject^("Shell.Application"^) > %_vbspath% || (echo/&echo/Unable to create %_vbspath% & endlocal &md; 2>nul &goto:eof) 
  echo/UAC.ShellExecute "%_batpath%", "", "", "runas", 1 >> %_vbspath% & echo/wscript.Quit(1)>> %_vbspath%
  :: Try to create %_batpath% file. If failed, exit with ERRORLEVEL 1
  echo/@%* > "%_batpath%" || (echo/&echo/Unable to create %_batpath% & endlocal &md; 2>nul &goto:eof)
  echo/@if %%errorlevel%%==9009 (echo/^&echo/Admin user could not read the batch file. If running from a mapped drive or UNC path, check if Admin user can read it.)^&echo/^& @if %%errorlevel%% NEQ 0 pause >> "%_batpath%"

  :: Run %_vbspath%, that calls %_batpath%, that calls the original file
  %_vbspath% && (echo/&echo/Failed to run VBscript %_vbspath% &endlocal &md; 2>nul & goto:eof)
  
  :: Vbscript has been run, exit with ERRORLEVEL -1
  echo/&echo/Elevation was requested on a new CMD window &endlocal &fc;: 2>nul & goto:eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

如何使用它的示例

:EXAMPLE
@echo off

 :: Run this script with elevation
 call :RequestAdminElevation "%~dpfs0" %* || goto:eof
 
  echo/I now have Admin rights!
  echo/
  echo/Arguments using %%args%%:    %args%
  echo/Arguments using %%*: %*
  echo/%%1= %~1
  echo/%%2= %~2
  echo/%%3= %~3

  echo/
  echo/Current Directory: %CD%
  echo/
  echo/This file: %0
  echo/

pause &goto:eof

[here you paste the RequestAdminElevation function code]

Here is my code! It looks big but it is mostly comment lines (the lines starting with ::).

Features:

  • Full argument forwarding

  • Does not change working folder

  • Error handling

  • Accepts paths with parenthesis (except for %TEMP% folder)

  • Supports UNC paths

  • Mapped folder check (Warn´s you if admin can´t access mapped drive)

  • Can be used as an external library (check my post at this topic: https://stackoverflow.com/a/30417025/4932683)

  • Can be called when/if needed anywhere in your code

Just attach this to the end of your batch file, or save it as a library (check above)

    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:RequestAdminElevation FilePath %* || goto:eof
:: 
:: By:   Cyberponk,     v1.6 - 05/05/2023 - Fixed crash when batch filename contained spaces
::          v1.5 - 10/06/2016 - Changed the admin rights test method from cacls to fltmc
::          v1.4 - 17/05/2016 - Added instructions for arguments with ! char
::          v1.3 - 01/08/2015 - Fixed not returning to original folder after elevation successful
::          v1.2 - 30/07/2015 - Added error message when running from mapped drive
::          v1.1 - 01/06/2015
:: 
:: Func: opens an admin elevation prompt. If elevated, runs everything after the function call, with elevated rights.
:: Returns: -1 if elevation was requested
::           0 if elevation was successful
::           1 if an error occured
:: 
:: USAGE:
:: If function is copied to a batch file:
::     call :RequestAdminElevation "%~dpf0" %* || goto:eof
::
:: If called as an external library (from a separate batch file):
::     set "_DeleteOnExit=0" on Options
::     (call :RequestAdminElevation "%~dpf0" %* || goto:eof) && CD /D %CD%
::
:: If called from inside another CALL, you must set "_ThisFile=%~dpf0" at the beginning of the file
::     call :RequestAdminElevation "%_ThisFile%" %* || goto:eof
::
:: If you need to use the ! char in the arguments, the calling must be done like this, and afterwards you must use %args% to get the correct arguments:
::      set "args=%* "
::      call :RequestAdminElevation .....   use one of the above but replace the %* with %args:!={a)%
::      set "args=%args:{a)=!%" 
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
setlocal ENABLEDELAYEDEXPANSION & set "_FilePath=%~1"
  if NOT EXIST "!_FilePath!" (echo/Read RequestAdminElevation usage information)
  :: UAC.ShellExecute only works with 8.3 filename, so use %~s1
  set "_FN=_%~ns1" & echo/%TEMP%| findstr /C:"(" >nul && (echo/ERROR: %%TEMP%% path can not contain parenthesis &pause &endlocal &fc;: 2>nul & goto:eof)
  :: Remove parenthesis from the temp filename
  set _FN=%_FN:(=%
  set _vbspath="%temp:~%\%_FN:)=%.vbs" & set "_batpath=%temp:~%\%_FN:)=%.bat"

  :: Test if we gave admin rights
  fltmc >nul 2>&1 || goto :_getElevation

  :: Elevation successful
  (if exist %_vbspath% ( del %_vbspath% )) & (if exist "%_batpath%" ( del "%_batpath%" )) 
  :: Set ERRORLEVEL 0, set original folder and exit
  endlocal & CD /D "%~dp1" & ver >nul & goto:eof

  :_getElevation
  echo/Requesting elevation...
  :: Try to create %_vbspath% file. If failed, exit with ERRORLEVEL 1
  echo/Set UAC = CreateObject^("Shell.Application"^) > %_vbspath% || (echo/&echo/Unable to create %_vbspath% & endlocal &md; 2>nul &goto:eof) 
  echo/UAC.ShellExecute "%_batpath%", "", "", "runas", 1 >> %_vbspath% & echo/wscript.Quit(1)>> %_vbspath%
  :: Try to create %_batpath% file. If failed, exit with ERRORLEVEL 1
  echo/@%* > "%_batpath%" || (echo/&echo/Unable to create %_batpath% & endlocal &md; 2>nul &goto:eof)
  echo/@if %%errorlevel%%==9009 (echo/^&echo/Admin user could not read the batch file. If running from a mapped drive or UNC path, check if Admin user can read it.)^&echo/^& @if %%errorlevel%% NEQ 0 pause >> "%_batpath%"

  :: Run %_vbspath%, that calls %_batpath%, that calls the original file
  %_vbspath% && (echo/&echo/Failed to run VBscript %_vbspath% &endlocal &md; 2>nul & goto:eof)
  
  :: Vbscript has been run, exit with ERRORLEVEL -1
  echo/&echo/Elevation was requested on a new CMD window &endlocal &fc;: 2>nul & goto:eof
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Example on how to use it

:EXAMPLE
@echo off

 :: Run this script with elevation
 call :RequestAdminElevation "%~dpfs0" %* || goto:eof
 
  echo/I now have Admin rights!
  echo/
  echo/Arguments using %%args%%:    %args%
  echo/Arguments using %%*: %*
  echo/%%1= %~1
  echo/%%2= %~2
  echo/%%3= %~3

  echo/
  echo/Current Directory: %CD%
  echo/
  echo/This file: %0
  echo/

pause &goto:eof

[here you paste the RequestAdminElevation function code]
时光匆匆的小流年 2024-08-21 17:42:32

另一种方法是在

  • 本地创建快捷方式并将其设置为调用管理员权限(属性、高级、以管理员身份运行)

,然后

  • 向用户发送快捷方式(或快捷方式的链接,而不是批处理文件本身的链接)。

Another approach is to

  • create a shortcut locally and set it to call for Admin permission (Properties, Advanced, Run as Admin)

and then

  • send your users the shortcut (or a link to the shortcut rather than one to the batch file itself).
滥情稳全场 2024-08-21 17:42:32

Ben Gripka 的解决方案会导致无限循环。他的批处理工作如下(伪代码):

IF "no admin privileges?"
    "write a VBS that calls this batch with admin privileges"
ELSE
    "execute actual commands that require admin privileges"

如您所见,如果 VBS 请求管理员权限失败,这会导致无限循环。

但是,尽管已成功请求管理员权限,但仍可能发生无限循环。

Ben Gripka 的批处理文件中的检查很容易出错。我尝试了该批处理,发现尽管检查失败,但管理员权限仍然可用。有趣的是,如果我从 Windows 资源管理器启动批处理文件,则检查按预期工作,但当我从 IDE 启动它时,检查却没有。

所以我建议使用两个单独的批处理文件。第一个生成调用第二个批处理文件的 VBS:

@echo off

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

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"

第二个名为“my_commands.bat”,位于与第一个批处理文件相同的目录中,包含您的实际命令:

pushd "%CD%"
CD /D "%~dp0"
REM Your commands which require admin privileges here

这不会导致无限循环,并且还删除了容易出错的管理员权限检查。

Ben Gripka's solution causes infinite loops. His batch works like this (pseudo code):

IF "no admin privileges?"
    "write a VBS that calls this batch with admin privileges"
ELSE
    "execute actual commands that require admin privileges"

As you can see, this causes an infinite loop, if the VBS fails requesting admin privileges.

However, the infinite loop can occur, although admin priviliges have been requested successfully.

The check in Ben Gripka's batch file is just error-prone. I played around with the batch and observed that admin privileges are available although the check failed. Interestingly, the check worked as expected, if I started the batch file from windows explorer, but it didn't when I started it from my IDE.

So I suggest to use two separate batch files. The first generates the VBS that calls the second batch file:

@echo off

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

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"

The second, named "my_commands.bat" and located in the same directory as the first contains your actual commands:

pushd "%CD%"
CD /D "%~dp0"
REM Your commands which require admin privileges here

This causes no infinite loops and also removes the error-prone admin privilege check.

人心善变 2024-08-21 17:42:32

另一个PowerShell解决方案...

这不是关于以管理员身份运行批处理脚本,而是如何从批处理中提升另一个程序...

我有一个exe的批处理文件“包装器”。它们具有相同的“根文件名”,但扩展名不同。我能够以管理员身份启动 exe,并将工作目录设置为包含脚本的目录,使用以下一行 powershell 调用:

@powershell "Start-Process -FilePath '%~n0.exe' -WorkingDirectory '%~dp0' -Verb RunAs"

更多信息

还有一大堆额外的 Start - 处理您可以应用的选项!查看:https: //learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6

请注意,我使用 @ 前缀。这相当于单行的 @echo off。我在这里使用 %~n0 来获取批处理脚本的“根名称”,然后连接 .exe 将其指向相邻的二进制文件。使用 %~dp0 提供批处理所在目录的完整路径。当然,-Verb RunAs 参数提供海拔

Another PowerShell Solution...

This is not about running a batch script as admin per, but rather how to elevate another program from batch...

I have a batch file "wrapper" for an exe. They have the same "root file name", but alternate extensions. I am able to launch the exe as admin, and set the working directory to the one containing the script, with the following one line powershell invocation:

@powershell "Start-Process -FilePath '%~n0.exe' -WorkingDirectory '%~dp0' -Verb RunAs"

More info

There are a whole slew of additional Start-Process options as well that you can apply! Check out: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6

Note that I use the @ prefix. That's equivalent to @echo off for the one line. I use %~n0 here to get the "root name" of the batch script, then I concatenate the .exe to point it the adjancent binary. The use of %~dp0 provides the full path to the directory which the batch resides. And, of course, the -Verb RunAs parameter provides the elevation.

小伙你站住 2024-08-21 17:42:32
@echo off 
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause

以上适用于我的 Windows 10 版本 1903

@echo off 
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause

The above works on my Windows 10 Version 1903

酷遇一生 2024-08-21 17:42:32

我知道这不是 OP 的解决方案,但由于我确信这里还有许多其他用例,所以我想我会分享。

我对这些答案中的所有代码示例都遇到了问题,但后来我发现:
http://www.robotronic.de/runasspcEn.html

它不仅允许您运行admin,它检查文件以确保它没有被篡改并安全地存储所需的信息。我承认它不是最明显的了解如何使用的工具,但对于我们这些编写代码的人来说它应该足够简单。

I know this is not a solution for OP, but since I'm sure there are many other use cases here, I thought I would share.

I've had problems with all the code examples in these answers but then I found :
http://www.robotronic.de/runasspcEn.html

It not only allows you to run as admin, it checks the file to make sure it has not been tampered with and stores the needed information securely. I'll admit it's not the most obvious tool to figure out how to use but for those of us writing code it should be simple enough.

还如梦归 2024-08-21 17:42:32

@echo offtitle 可以出现在这段代码之前:

net session>nul 2>&1
if %errorlevel%==0 goto main
echo CreateObject("Shell.Application").ShellExecute "%~f0", "", "", "runas">"%temp%/elevate.vbs"
"%temp%/elevate.vbs"
del "%temp%/elevate.vbs"
exit

:main
    <code goes here>
exit

如果您不需要担心以下问题,那么许多其他答案都是多余的:

  • 参数
  • 工作目录(< code>cd %~dp0 将更改为包含批处理文件的目录)

@echo off and title can come before this code:

net session>nul 2>&1
if %errorlevel%==0 goto main
echo CreateObject("Shell.Application").ShellExecute "%~f0", "", "", "runas">"%temp%/elevate.vbs"
"%temp%/elevate.vbs"
del "%temp%/elevate.vbs"
exit

:main
    <code goes here>
exit

A lot of the other answers are overkill if you don't need to worry about the following:

  • Parameters
  • Working Directory (cd %~dp0 will change to the directory containing the batch file)
江南烟雨〆相思醉 2024-08-21 17:42:32

还有来自 这篇文章 的 FSUTIL 查询,该查询也链接在 ss64.com 具有以下代码:

@Echo Off
Setlocal
:: First check if we are running As Admin/Elevated
FSUTIL dirty query %SystemDrive% >nul
if %errorlevel% EQU 0 goto START

::Create and run a temporary VBScript to elevate this batch file
   Set _batchFile=%~f0
   Set _Args=%*
   :: double up any quotes
   Set _batchFile=""%_batchFile:"=%""
   Set _Args=%_Args:"=""%

   Echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\~ElevateMe.vbs"
   Echo UAC.ShellExecute "cmd", "/c ""%_batchFile% %_Args%""", "", "runas", 1 >> "%temp%\~ElevateMe.vbs"

   cscript "%temp%\~ElevateMe.vbs" 
   Exit /B

:START
:: set the current directory to the batch file location
cd /d %~dp0
:: Place the code which requires Admin/elevation below
Echo We are now running as admin [%1] [%2]
pause

只要 FSUTIL 存在,它就是一个可靠的替代方案。

There's also the FSUTIL query from this post which is also linked at ss64.com that has the following code:

@Echo Off
Setlocal
:: First check if we are running As Admin/Elevated
FSUTIL dirty query %SystemDrive% >nul
if %errorlevel% EQU 0 goto START

::Create and run a temporary VBScript to elevate this batch file
   Set _batchFile=%~f0
   Set _Args=%*
   :: double up any quotes
   Set _batchFile=""%_batchFile:"=%""
   Set _Args=%_Args:"=""%

   Echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\~ElevateMe.vbs"
   Echo UAC.ShellExecute "cmd", "/c ""%_batchFile% %_Args%""", "", "runas", 1 >> "%temp%\~ElevateMe.vbs"

   cscript "%temp%\~ElevateMe.vbs" 
   Exit /B

:START
:: set the current directory to the batch file location
cd /d %~dp0
:: Place the code which requires Admin/elevation below
Echo We are now running as admin [%1] [%2]
pause

As long as FSUTIL is around, it's a reliable alternative.

那伤。 2024-08-21 17:42:32

使用 mshta 提示输入管理员权限:

@echo off
net session >nul 2>&1 && goto :admintasks
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
exit /b
:admintasks
rem ADMIN TASKS HERE

或者使用 powershell:

powershell -c Start-Process "%~nx0" -Verb runas

Use mshta to prompt for admin rights:

@echo off
net session >nul 2>&1 && goto :admintasks
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
exit /b
:admintasks
rem ADMIN TASKS HERE

Or, using powershell:

powershell -c Start-Process "%~nx0" -Verb runas
笙痞 2024-08-21 17:42:32

由于我在无限循环(使用 Win 7 Pro)中遇到此脚本弹出新命令提示符并再次运行的问题,我建议您尝试另一种方法:如何自动提升我的批处理文件,以便它从如果需要 UAC 管理员权限?

请注意,您必须将其添加到脚本末尾,如编辑中所述,以便在权限提升后返回到脚本目录:
cd /d %~dp0

Since I have troubles with this script popping up a new command prompt with itself run again, in infinite loop (using Win 7 Pro), I suggest you try another approach :How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

Be careful, you have to add this at the end of script, as stated in an edit, so that you are back to script directory after privileges were elevated :
cd /d %~dp0

不乱于心 2024-08-21 17:42:32

根据 toster-cx 的帖子和本页面上其他有趣的帖子,我深入了解了如何配置和解决我的问题。我遇到了类似的问题,我希望磁盘清理实用程序每周在周一和周四的午餐时间(比如下午 2 点)运行两次。然而,这需要更高的权利。

共享批处理文件,这可能会帮助像我这样的其他初学者 -

@echo off
echo  Welcome to scheduling 'PC Maintenance Activity'
ping localhost -n 3 >nul
echo -- Step - 1 of 3 : Please give 'Admin' rights on next screen
ping localhost -n 5 >nul
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit)
cls
echo -- Step - 2 of 3 : In next screen, select temp areas for cleaning 
during routine scheduled activity
ping localhost -n 3 >nul
C:\Windows\System32\cleanmgr.exe /sageset:112
cls
echo    Now scheduling maintenance activity...
SchTasks /Create /SC WEEKLY /D MON,THU /TN PC_Cleanup /TR 
"C:\Windows\System32\cleanmgr.exe "/sagerun:112 /ST 14:00

cls

echo                         -- Thanks for your co-operation --
echo                    -- Maintenance activity is scheduled for --
echo                       -- Every Monday and Thursday at 2 pm --

ping localhost -n 10 >nul

非常感谢这个论坛和 Rems 在这里发帖 [https://www.petri.com/forums/forum/windows-scripting/general-scripting/ 32313-schtasks-exe-need-to-pass-parameters-to-script][1]

他的帖子有助于在安排任务时配置可选参数。

Based on post by toster-cx and other interesting posts on this page, I got insight on how to configure and solve my problem. I had similar issue where I wished that Disk Cleanup utility runs every week twice on Monday and Thursday during lunch hours (say 2 pm). However, this required elevated rights.

Sharing batch file which might help other beginners like me -

@echo off
echo  Welcome to scheduling 'PC Maintenance Activity'
ping localhost -n 3 >nul
echo -- Step - 1 of 3 : Please give 'Admin' rights on next screen
ping localhost -n 5 >nul
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit)
cls
echo -- Step - 2 of 3 : In next screen, select temp areas for cleaning 
during routine scheduled activity
ping localhost -n 3 >nul
C:\Windows\System32\cleanmgr.exe /sageset:112
cls
echo    Now scheduling maintenance activity...
SchTasks /Create /SC WEEKLY /D MON,THU /TN PC_Cleanup /TR 
"C:\Windows\System32\cleanmgr.exe "/sagerun:112 /ST 14:00

cls

echo                         -- Thanks for your co-operation --
echo                    -- Maintenance activity is scheduled for --
echo                       -- Every Monday and Thursday at 2 pm --

ping localhost -n 10 >nul

Thanks a lot for this forum and Rems POST here [https://www.petri.com/forums/forum/windows-scripting/general-scripting/32313-schtasks-exe-need-to-pass-parameters-to-script][1]

His post helped for configuring optional argument while scheduling the task.

橙味迷妹 2024-08-21 17:42:32

您无法从批处理文件请求管理员权限,但您可以在 %temp% 中编写一个 Windows 脚本主机脚本并运行该脚本(进而以管理员身份执行您的批处理)您想要在 Shell 中调用 ShellExecute 方法。以“runas”作为动词的应用程序对象

You can't request admin rights from a batch file, but you could write a windows scripting host script in %temp% and run that (and that in turn executes your batch as admin) You want to call the ShellExecute method in the Shell.Application object with "runas" as the verb

末が日狂欢 2024-08-21 17:42:32

我使用了多个示例来将这个工作衬里修补在一起。

这将以 ADMIN + 最大化窗口 的形式打开批处理脚本,

只需将以下代码之一添加到批处理脚本的顶部即可。
两种方法都可以,只是编码方式不同。

我相信第一个示例响应最快,因为 /d 开关禁用了我已启用的 doskey 命令。

示例一

@ECHO OFF
IF NOT "%1"=="MAX" (powershell -WindowStyle Hidden -NoProfile -Command {Start-Process CMD -ArgumentList '/D,/C' -Verb RunAs} & START /MAX CMD /D /C %0 MAX & EXIT /B)
:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

:: Your original batch code here:

:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

示例二

@ECHO OFF
IF NOT "%1"=="MAX" (powershell -WindowStyle Hidden -NoProfile -Command "Start-Process CMD -ArgumentList '/C' -Verb RunAs" & START /MAX CMD /C "%0" MAX & EXIT /B)
:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

:: Your original batch code here:

:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

请参阅下文使用原始批处理代码时的建议

将原始批处理代码完整放置

只是因为最顶部的第一行代码有@ECHO OFF
并不意味着如果您的原始脚本不应该再次包含它
也有。

这确保了当脚本在现在在管理中运行的新窗口中重新启动时
您不会丢失预期的脚本参数/属性的模式...
例如当前工作目录、本地变量等

您可以从以下命令开始以避免其中一些问题

:: Make sure to use @ECHO OFF if your original code had it
@ECHO OFF
:: Avoid clashing with other active windows variables with SETLOCAL
SETLOCAL
:: Nice color to work with using 0A
COLOR 0A
:: Give your script a name
TITLE NAME IT!

:: Ensure your working directory is set where you want it to be
:: the following code sets the working directory to the script directory folder
PUSHD "%~dp0"

THE REST OF YOUR SCRIPT HERE...

:: Signal the script is finished in the title bar
ECHO.
TITLE Done! NAME IT!
PAUSE
EXIT

I used multiple examples to patch this working one liner together.

This will open your batch script as an ADMIN + Maximized Window

Just add one of the following codes to the top of your batch script.
Both ways work, just different ways to code it.

I believe the first example responds the quickest due to /d switch disabling my doskey commands that I have enabled..

EXAMPLE ONE

@ECHO OFF
IF NOT "%1"=="MAX" (powershell -WindowStyle Hidden -NoProfile -Command {Start-Process CMD -ArgumentList '/D,/C' -Verb RunAs} & START /MAX CMD /D /C %0 MAX & EXIT /B)
:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

:: Your original batch code here:

:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

EXAMPLE TWO

@ECHO OFF
IF NOT "%1"=="MAX" (powershell -WindowStyle Hidden -NoProfile -Command "Start-Process CMD -ArgumentList '/C' -Verb RunAs" & START /MAX CMD /C "%0" MAX & EXIT /B)
:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

:: Your original batch code here:

:--------------------------------------------------------------------------------------------------------------------------------------------------------------------

See below for recommendations when using your original batch code

Place the original batch code in it's entirety

Just because the first line of code at the very top has @ECHO OFF
doesn't mean you should not include it again if your original script
has it as well.

This ensures that when the script get's restarted in a new window now running in admin
mode that you don't lose your intended script parameters/attributes...
Such as the current working directory, your local variables, and so on

You could beginning with the following commands to avoid some of these issues

:: Make sure to use @ECHO OFF if your original code had it
@ECHO OFF
:: Avoid clashing with other active windows variables with SETLOCAL
SETLOCAL
:: Nice color to work with using 0A
COLOR 0A
:: Give your script a name
TITLE NAME IT!

:: Ensure your working directory is set where you want it to be
:: the following code sets the working directory to the script directory folder
PUSHD "%~dp0"

THE REST OF YOUR SCRIPT HERE...

:: Signal the script is finished in the title bar
ECHO.
TITLE Done! NAME IT!
PAUSE
EXIT
拥抱没勇气 2024-08-21 17:42:32

少&快速

@echo off
fltmc >nul || (echo CreateObject^("Shell.Application"^).ShellExecute "%~0", "", "", "runas">"%temp%/$el.vbs"& "%temp%/$el.vbs"& exit)
fltmc >nul && echo A.D.M.I.N || echo U.S.E.R
pause

LESS & FAST

@echo off
fltmc >nul || (echo CreateObject^("Shell.Application"^).ShellExecute "%~0", "", "", "runas">"%temp%/$el.vbs"& "%temp%/$el.vbs"& exit)
fltmc >nul && echo A.D.M.I.N || echo U.S.E.R
pause
烂人 2024-08-21 17:42:32

使用 runas 命令。但是,我认为您无法轻松通过电子邮件发送 .bat 文件。

use the runas command. But, I don't think you can email a .bat file easily.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文