Running a command as Administrator using PowerShell?

后端 未结 26 3391
粉色の甜心
粉色の甜心 2020-11-22 09:41

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

26条回答
  •  再見小時候
    2020-11-22 10:15

    Using

    #Requires -RunAsAdministrator

    has not been stated, yet. It seems to be there only since PowerShell 4.0.

    http://technet.microsoft.com/en-us/library/hh847765.aspx

    When this switch parameter is added to your requires statement, it specifies that the Windows PowerShell session in which you are running the script must be started with elevated user rights (Run as Administrator).

    To me, this seems like a good way to go about this, but I'm not sure of the field experience, yet. PowerShell 3.0 runtimes probably ignore this, or even worse, give an error.

    When the script is run as a non-administrator, the following error is given:

    The script 'StackOverflow.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.

    + CategoryInfo          : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ScriptRequiresElevation
    

提交回复
热议问题