
Помещение этого кода в скрипт 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