如果將 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

相關內容