사용자 프로필에 함수로 작성하면 PowerShell 자체 상승 스크립트가 작동하지 않습니다.

사용자 프로필에 함수로 작성하면 PowerShell 자체 상승 스크립트가 작동하지 않습니다.

이 코드를 PowerShell 스크립트에 넣으면 자동으로 승격됩니다.

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
        [Security.Principal.WindowsBuiltInRole] 'Administrator'))
    {
        Start-Process PowerShell -ArgumentList "-File", ('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
        exit
    }

#Main code here

그러나 PS 사용자 프로필에서 사용할 수 있도록 함수를 만들고 스크립트에서 해당 함수를 호출하면 작동하지 않습니다. 새 PowerShell 관리 세션이 열렸지만 기본 스크립트 코드를 읽을 수 없습니다.

function Elevate-NoAdmin
{
    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
        [Security.Principal.WindowsBuiltInRole] 'Administrator'))
    {
        Start-Process PowerShell -ArgumentList "-File", ('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
        exit
    }
}

왜 함수로 작동하지 않는지, 작동하게 만들 수 있는지에 대한 아이디어가 있습니까?

답변1

PS 사용자 프로필의 함수에 대한 변수로 스크립트 경로를 쉽게 전달하는 매개변수를 정의하여 함수를 다시 작성했습니다. 그렇지 않으면 PS 사용자 프로필의 경로가 대신 사용됩니다.

function Elevate-NoAdmin
{
    param(
    [Parameter(Mandatory)]
    [String]$ScriptPath
    )
    
    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::
        GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator'))
    {
        Start-Process -FilePath PowerShell.exe -Args "-File `"$ScriptPath`"" -Verb RunAs
        exit
    }
}

스크립트에서:

Elevate-NoAdmin $PSCommandPath

#Main code here

또는

Elevate-NoAdmin $MyInvocation.MyCommand.Path

#Main code here

관련 정보