2020年7月3日金曜日

◆管理者として実行する

以前メモしておいたものを実際に使う機会があったのでUPしておく。
かな~り昔にメモしておいたものなので今となってはもっとスマートなやり方があるのかもしれません。

$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object Security.Principal.WindowsPrincipal $identity
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false)
{
     $Args = '-noprofile -nologo -executionpolicy bypass -file "{0}"' -f
     $MyInvocation.MyCommand.Path
     $MyInvocation.MyCommand.Path
     Start-Process -FilePath 'powershell.exe' -ArgumentList $Args -Verb RunAs
     exit
}

#管理者として実行が必要な処理を以下に記述



上記の処理をスクリプトの先頭に記述しておくと自分自身を管理者実行で呼びなおしてくれるというもの。

これを独立させて、実行するスクリプトを引数で与えても良いのかもしれませんね。