Running a command as Administrator using PowerShell?

后端 未结 26 3446
粉色の甜心
粉色の甜心 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:13

    Here's a self-elevating snippet for Powershell scripts which preserves the working directory:

    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
        exit;
    }
    
    # Your script here
    

    Preserving the working directory is important for scripts that perform path-relative operations. Almost all of the other answers do not preserve this path, which can cause unexpected errors in the rest of the script.

    If you'd rather not use a self-elevating script/snippet, and instead just want an easy way to launch a script as adminstrator (eg. from the Explorer context-menu), see my other answer here: https://stackoverflow.com/a/57033941/2441655

提交回复
热议问题