Home >
Windows にまつわる e.t.c.
PowerShellが管理権限で実行されているか確認する
PowerShellのスクリプトで運用管理をしていると、管理権限でスクリプトを実行しないとエラーになるケースがよくあります。
スクリプトの最初で管理権限実行されているか確認すれば余計なエラーでがっかりすることはありませんね。
# 管理権限で実行されているか
if (-not(([Security.Principal.WindowsPrincipal] `
[Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"`
))) {
echo "○●○●○● 実行には管理権限が必要です ○●○●○●"
}
|
ワンライナーで書いてゴチャている感じなので、行を分けて書くとこんな感じです
# 管理権限で実行されているか
$CurrentUserWindowsIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$CurrentUserWindowsPrincipal = New-Object Security.Principal.WindowsPrincipal($CurrentUserWindowsIdentity)
$IsAdministrator = $CurrentUserWindowsPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if(-not $IsAdministrator){
echo "○●○●○● 実行には管理権限が必要です ○●○●○●"
}
|


Copyright © MURA
All rights reserved.