PowerTip: Specify that a script requires admin privileges to run

Summary: Learn how to require admin privileges to run a Windows PowerShell script.

Hey, Scripting Guy! Question How can I make sure that my Windows PowerShell script has administrator privileges to run?

Hey, Scripting Guy! Answer Use the #Requires directive and specify RunAsAdministrator. Here is an example:

#Requires -RunAsAdministrator

The Doctor

Comments (8)

  1. And does that work for Powershell 2.0 and up, or what?

  2. John says:

    Hello, you do not need to remove the # ? This will not be interpreted as a comment ?

    1. Hi John,

      In the previous post of this amazing blog you can find a post by June Blender, the main topic is something completely different, but there is a small section where she covers this topic, and most importantly she provided with the link to the About Topics regarding “Requires”.

      The link for her post: https://blogs.technet.microsoft.com/heyscriptingguy/2016/04/25/how-to-answer-a-technical-question-a-guide-for-presenters/
      The link for the About_Requires: https://technet.microsoft.com/library/hh847765.aspx

    2. Steve says:

      Nope, PowerShell will see #Requires and its properties or requirements. Type “help requires” into your ps console for more details.

  3. Andreas says:

    thank you for sharing this.

    What is the correct way to specify multiple #Requires Parameters (i.e. -Version and -RunAsAdministrator)

    Have a nice day

  4. Jason W says:

    @Nikolaj #Requires is a feature of PowerShell 3.0 and up but PowerShell 4.0 is required do use the -RunAsAdministrator switch

    @John – The # needs to be there. Run: ‘Get-Help about_requires’ for more details

  5. kbotha says:

    This only works with PowerShell 4.0 and up

  6. nebule-nz says:

    looking at the documentation it isn’t a mistake! I will be using this for sure, thanks.

    Here’s about_requires – https://technet.microsoft.com/en-us/library/hh847765.aspx

Skip to main content