
このコードを 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