PowerShell 스크립트에서 관리자 권한으로 실행 중인지 어떻게 확인할 수 있습니까?


답변:


33
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

( 명령 줄 안전 트릭에서 )


2
$ currentPrincipal = 새 개체 Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity] :: GetCurrent ()) & {if ($ currentPrincipal.IsInRole ([Security.Principal.WindowsBuiltInRole] :: Administrator)) {(get- 호스트) .UI.RawUI.Backgroundcolor = "DarkRed"clear-host write-host "경고 : PowerShell이 ​​관리자로 실행 중입니다
— .`n

첫 번째 줄 : 마지막 닫는 괄호)가 없습니다. 6 자 미만으로 변경하면 문제를 해결할 수 없습니다.
— Xavier Nicollet

57

당신이 사용할 수있는 파워 쉘 4.0은 필요 스크립트의 상단에 :

#Requires -RunAsAdministrator

출력 :

'MyScript.ps1'스크립트에는 관리자로 실행하기위한 "#requires"문이 포함되어 있으므로 실행할 수 없습니다. 현재 Windows PowerShell 세션이 관리자로 실행되고 있지 않습니다. 관리자 권한으로 실행 옵션을 사용하여 Windows PowerShell을 시작한 다음 스크립트를 다시 실행하십시오.


내가 찾던 것이 아니지만 여전히 매우 유용합니다. 고마워 에디!
— Michael Kelley

33
function Test-Administrator  
{  
    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)  
}

위 기능을 실행하십시오. 결과가 True이면 사용자에게 관리자 권한이 있습니다.


4
이는 스크립트를 실행하는 사용자가 컴퓨터의 관리자인지 여부를 결정하며 스크립트가 현재 관리 권한 으로 실행 되고 있는지 여부를 결정하지 않습니다 . 즉, 사용자가 "관리자 권한으로 실행"을 사용하여 명령 셸을 시작하지 않은 경우에도 여전히 true를 반환합니다.
— 전체론 개발자

2
@HolisticDeveloper, 그건 맞지 않습니다. 높이 올리지 않으면 거짓을 반환합니다.
— charleswj81

@ charleswj81은 현재 Holistic Developer가 설명하는 동작을 관찰합니다.
— zneak

나는 당신이 세미콜론이 필요하다고 생각하지 않습니다 ...하지만 그것은 그것이 오류를 던질 것이라고 생각하지 않는다고 말했습니다.
— Kolob Canyon

2018 년 현재 Win10에서 작동합니다. 현재 사용자 계정이 상승하지 않으면 False를 반환하고 powershell이 ​​상승하면 True를 반환합니다.
— arberg

0

그러면 관리자인지 확인하고 그렇지 않은 경우 PowerShell ISE에서 관리자로 다시 열립니다.

도움이 되었기를 바랍니다!

    $ver = $host | select version
    if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}

    # Verify that user running script is an administrator
    $IsAdmin=[Security.Principal.WindowsIdentity]::GetCurrent()
    If ((New-Object Security.Principal.WindowsPrincipal $IsAdmin).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) -eq $FALSE)
    {
      "`nERROR: You are NOT a local administrator.  Run this script after logging on with a local administrator account."
        # We are not running "as Administrator" - so relaunch as administrator

        # Create a new process object that starts PowerShell
        $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell_ise";

        # Specify the current script path and name as a parameter
        $newProcess.Arguments = $myInvocation.MyCommand.Definition;

        # Indicate that the process should be elevated
        $newProcess.Verb = "runas";

        # Start the new process
        [System.Diagnostics.Process]::Start($newProcess);

        # Exit from the current, unelevated, process
        exit
    }

0

위의 답변을 조합하여 스크립트 시작 부분에 다음과 같은 것을 사용할 수 있습니다.

# todo: put this in a dedicated file for reuse and dot-source the file
function Test-Administrator  
{  
    [OutputType([bool])]
    param()
    process {
        [Security.Principal.WindowsPrincipal]$user = [Security.Principal.WindowsIdentity]::GetCurrent();
        return $user.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator);
    }
}

if(-not (Test-Administrator))
{
    # TODO: define proper exit codes for the given errors 
    Write-Error "This script must be executed as Administrator.";
    exit 1;
}

$ErrorActionPreference = "Stop";

# do something

또 다른 방법은이 줄로 스크립트를 시작하여 관리자 권한으로 시작하지 않을 때 스크립트가 실행되지 않도록하는 것입니다.

#Requires -RunAsAdministrator

1
불행히도 이것은 작동하지 않습니다. 스크립트가 높은 권한으로 실행되지 않으면로드되지 않으며 사용자 지정 오류 메시지가 표시되지 않습니다.
— JamesQMurphy

감사. 위의 답변을 수정했습니다.
— MovGP0
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.