Running a command as Administrator using PowerShell?

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

提交回复
热议问题