1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellでスクリプトが管理者で実行されているか確認する

Posted at

PowerShellでスクリプトを作成する場合、スクリプトの実行時に管理者権限かどうかをチェックしたい場合があるかと思います。

PowerShellではRequiresステートメントが用意されており。
こちらを利用すると、必要な条件を満たしていない場合のスクリプト実行を制限できます。

このRequiresステートメントの中に管理者で開始する条件があります。

ドキュメント

about_Requires

#Requires RunAsAdministrator

runasadministrator

#RequiresRunAsAdministratorを利用して、管理者で開始されるよう制限をかけます。

RunAsAdministrator.ps1
#Requires -RunAsAdministrator

Write-host "HelloWorld"

上記スクリプトファイルRunAsAdministrator.ps1を用意し、管理者特権ではない状態で実行すると下記の通りエラーとなります。

image.png

エラーメッセージにAdministratorで実行してくださいと出ています。

なおドキュメントに記載ありますが、このRunAsAdministratorが使えるようになったのはPowerShell 4.0からとなるようです。
2022年現在、PowerShell 4.0の環境をさわることは減りましたが、少しだけ気にしておきたいポイントではあります。

余談 WindowsPrincipal.IsInRole メソッド で管理者実行か判定

WindowsPrincipal.IsInRole メソッド

.NETのWindowsPrincipalクラスのIsInRoleメソッドで管理者実行されているか確認ができます。

PowerShellでは下記を実行し、Trueとなれば管理者実行と判断できます。

[System.Security.Principal.WindowsPrincipal]::new([System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

image.png

上記画像では、実行結果がFalseとなっているため、管理者では実行されていないと判断できます。

総評

PowerShellスクリプトでは簡易に管理者実行に制限でき便利です。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?