Running a command as Administrator using PowerShell?

后端 未结 26 2887
粉色の甜心
粉色の甜心 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.

    0 讨论(0)
  • 2020-11-22 10:14

    It turns out it was too easy. All you have to do is run a cmd as administrator. Then type explorer.exe and hit enter. That opens up Windows Explorer. Now right click on your PowerShell script that you want to run, choose "run with PowerShell" which will launch it in PowerShell in administrator mode.

    It may ask you to enable the policy to run, type Y and hit enter. Now the script will run in PowerShell as administrator. In case it runs all red, that means your policy didn't take affect yet. Then try again and it should work fine.

    0 讨论(0)
  • 2020-11-22 10:15

    Using

    #Requires -RunAsAdministrator

    has not been stated, yet. It seems to be there only since PowerShell 4.0.

    http://technet.microsoft.com/en-us/library/hh847765.aspx

    When this switch parameter is added to your requires statement, it specifies that the Windows PowerShell session in which you are running the script must be started with elevated user rights (Run as Administrator).

    To me, this seems like a good way to go about this, but I'm not sure of the field experience, yet. PowerShell 3.0 runtimes probably ignore this, or even worse, give an error.

    When the script is run as a non-administrator, the following error is given:

    The script 'StackOverflow.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.

    + CategoryInfo          : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ScriptRequiresElevation
    
    0 讨论(0)
  • 2020-11-22 10:20

    The code posted by Jonathan and Shay Levy did not work for me.

    Please find the working code below:

    If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    {   
    #"No Administrative rights, it will display a popup window asking user for Admin rights"
    
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments
    
    break
    }
    #"After user clicked Yes on the popup, your file will be reopened with Admin rights"
    #"Put your code here"
    
    0 讨论(0)
  • 2020-11-22 10:22

    Self elevating PowerShell script

    Windows 8.1 / PowerShell 4.0 +

    One line :)

    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
    
    # Your script here
    
    0 讨论(0)
  • 2020-11-22 10:22

    You can create a batch file (*.bat) that runs your powershell script with administrative privileges when double-clicked. In this way, you do not need to change anything in your powershell script.To do this, create a batch file with the same name and location of your powershell script and then put the following content in it:

    @echo off
    
    set scriptFileName=%~n0
    set scriptFolderPath=%~dp0
    set powershellScriptFileName=%scriptFileName%.ps1
    
    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%\`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"
    

    That's it!

    Here is the explanation:

    Assuming your powershell script is in the path C:\Temp\ScriptTest.ps1, your batch file must have the path C:\Temp\ScriptTest.bat. When someone execute this batch file, the following steps will occur:

    1. The cmd will execute the command

      powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
      
    2. A new powershell session will open and the following command will be executed:

      Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
      
    3. Another new powershell session with administrative privileges will open in the system32 folder and the following arguments will be passed to it:

      -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
      
    4. The following command will be executed with administrative privileges:

      cd "C:\Temp"; & ".\ScriptTest.ps1"
      

      Once the script path and name arguments are double quoted, they can contain space or single quotation mark characters (').

    5. The current folder will change from system32 to C:\Temp and the script ScriptTest.ps1 will be executed. Once the parameter -NoExit was passed, the window wont be closed, even if your powershell script throws some exception.

    0 讨论(0)
提交回复
热议问题