r/PowerShell • u/SuppaDumDum • Jan 27 '26
Solved Is there any reliable way to get a powershell script to run as admin (and request admin when run normally)?
A year ago I spent days looking up and trying different suggestions to get powershell to do it. Which probably means there isn't any reliable way. But this year I'll just ask, is there any actual reliable way to do it?
I could of course just right-click the ps1 script and run as admin.
But I was looking for a way to get the script itself to request admin permissions. As in: I run the script normally, the script itself requests elevation, I accept, and it runs as admin
PS: Iirc one of the hacks was to make two scripts, an auxiliary that we run and it will call the second script explicitly with admin perms.
11
u/Leyous22 Jan 27 '26
I often use this on top of my ps1 files:
4
u/SuppaDumDum Jan 27 '26
Someone made a comment, and it was malformated due to reddit and the person seems to have deleted it. Anyway, in response to that comment:
Reddit is messing something up, but it seems like it works? Thank you!
Fixing the formatting:
first
second
4
u/Any-Virus7755 Jan 27 '26
Use an RMM and run as system
2
u/sdsalsero Jan 28 '26
FYI - those 'self-elevation' snippets have to be formatted for PS5 vs PS7, i.e., different executables
7
u/seaboypc Jan 27 '26
Lately I've been just using
Requires -RunAsAdministrator
Simple to code, provides good feedback to the user.
1
u/AdeelAutomates Jan 27 '26
How is it being triggered? Some one without admin access has to run it manually?
1
u/SonicPimp9000 Jan 27 '26
Try to run it on a service account with admin permissions.
1
u/SVD_NL Jan 27 '26
I don't have the example snippet at hand, but you essentially check for admin perms, and if you're not an admin, you grab the current command path using
$PSCommandPath, then start a new powershell process with that path, using runas to elevate to admin.1
u/OlivTheFrog Jan 27 '26
Hi u/SuppaDumDum
I've just created a gist with a powershell function to do this : Just include the function at the beginning of your script and call it. If the script is not running in RunAsAdmin mode, this launches a new instance of powershell in this mode and re-run your script.
https://gist.github.com/Rapidhands/bf897c3fe0d750134c2ef4b04d3d001d
regards
1
u/krisdb2009 Jan 27 '26
1
u/BlackV Jan 27 '26
But I was looking for a way to get the script itself to request admin permissions. As in: I run the script normally, the script itself requests elevation, I accept, and it runs as admin
-verb runas1
u/bobsmon Jan 28 '26
One way is set a scheduled task. Set the task that it can be run on command. You can create a batch to trigger the task. Put it as an icon on the desktop for nonadmin to click.
1
u/g3n3 Jan 28 '26
I prefer gsudo or there is win 11 sudo which can be enabled.