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
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:
The cmd will execute the command
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
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
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\""
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 ('
).
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.