Running a command as Administrator using PowerShell?

后端 未结 26 3336
粉色の甜心
粉色の甜心 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:00

    I haven't seen my own way of doing it before, so, try this out. It is way easier to follow and has a much smaller footprint:

    if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
        Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
        }
    

    Very simply, if the current Powershell session was called with administrator privileges, the Administrator Group well-known SID will show up in the Groups when you grab the current identity. Even if the account is a member of that group, the SID won't show up unless the process was invoked with elevated credentials.

    Nearly all of these answers are a variation on Microsoft's Ben Armstrong's immensely popular method of how to accomplish it while not really grasping what it is actually doing and how else to emulate the same routine.

提交回复
热议问题