How can I run a script with both user and admin privileges?

August 6, 2025 5 answers
Asked by CreativeCoder42
I'm trying to develop a comprehensive remediation script that will help users with frequent issues. The challenge I'm facing is that some parts of the script need to run under the user's context, while others require admin privileges. My idea is to have the user execute the script, and it would elevate itself as needed. However, I don't want a bunch of prompts popping up asking for admin consent for every single task that requires elevation. Is there a way to establish an elevated PowerShell session once from the main script that I can reuse for multiple commands? Or would it be better to compile a list of actions requiring admin privileges and send that to PowerShell using the 'runas' verb?

Answers

SkepticalScripter
I'm curious why you need admin privileges in the first place? Some tasks may not actually require it, which could simplify your script.
Reply to this answer
AdminGuru99
You can use the `Enter-PSSession` command with your admin credentials to connect to the device. As long as you aren't hitting any double-hop issues, you shouldn't need further user input. Just remember, you'll need to enable PowerShell remoting first.
Reply to this answer
LinuxNinja
One workaround for this could be creating an on-demand scheduled task that's only editable by admins but can be run by regular users. This lets users execute scripts as admins without needing admin approval each time, but it does mean you'll have to handle scheduled task setup.
Reply to this answer
NewbieNerd2000
If you're looking for a more straightforward approach to elevation, consider using the `gsudo` command. It's designed to help with elevation in specific scenarios, but make sure it fits your needs!
Reply to this answer
PowershellPro
Using PowerShell remoting is a solid method to maintain an elevated session, but it would run separately from your main script. Here's a basic command: `$adminguy = Get-Credential -Credential 'domainnameadminguy'; Start-Process -FilePath PowerShell.exe -Credential $adminguy -Command 'Start-Process -FilePath PowerShell.exe -Verb RunAs'`. Just keep in mind that the user will need to click 'yes' on the prompt.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions