How can I run a PowerShell script as admin from a separate file?

August 9, 2025 3 answers
Asked by nearly horizontal
I'm putting together backup scripts for my hard drives and managed to write a shared library of hashtables, variables, and functions for various maintenance tasks. Instead of copying my library into each script, I found the dot method to include files in PowerShell, which seemed perfect! However, I ran into a roadblock. I took some code to run PowerShell in administrator mode and put it inside a function. The problem is that when I call this function from a separate file, PowerShell immediately exits. The code does work perfectly when placed directly in the backup script. Is there a more efficient way to manage this without having to duplicate the admin code in every script? I'm looking for a practical code example since my experience with PowerShell is pretty basic.

Answers

thereabouts
It sounds like your issue is linked to how User Access Control (UAC) operates. Elevating a process without prompting for credentials can often lead to unwanted behavior, like what you're experiencing. The simplest fix would be to run your script as an administrator from the start. However, if that's not feasible, you really might want to explore the PowerShell training guide, as it might save you some headaches in the long run!

Puzzlewise: I get what you're saying, but the UAC prompt appears when the code is in a separate file. It terminates right after that! When it's in the backup script, it runs fine. I definitely need a working example rather than just advice.

Reply to this answer
!702 archive drawer
Just a quick tip regarding your formatting: when quoting variables in PowerShell, remember that single quotes (' ') treat everything as a string, while double quotes (" ") will resolve variables. That could be affecting your script's behavior. Check out some examples of similar command lines for elevation hereโ€”there's plenty of great info within this community!
Reply to this answer
mint_condition
Also, for future posts, use a PowerShell editor to format your code properly. Highlight your code and hit tab to indent, then copy and paste here for better readability! It makes it easier for others to help out, and you might get quicker responses.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions