Running a command as Administrator using PowerShell?

后端 未结 26 2948
粉色の甜心
粉色の甜心 2020-11-22 09:41

You know how if you\'re the administrative user of a system and you can just right click say, a batch script and run it as Administrator without entering the administrator p

26条回答
  •  花落未央
    2020-11-22 10:14

    The most reliable way I've found is to wrap it in a self-elevating .bat file:

    @echo off
    NET SESSION 1>NUL 2>NUL
    IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
    CD %~dp0
    MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
    EXIT
    
    :ADMINTASKS
    
    powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"
    
    EXIT
    

    The .bat checks if you're already admin and relaunches the script as Administrator if needed. It also prevents extraneous "cmd" windows from opening with the 4th parameter of ShellExecute() set to 0.

提交回复
热议问题