Powershell停止脚本,如果它不作为管理员运行

问题描述:

我有一个脚本,当我安装新的笔记本电脑时使用。Powershell停止脚本,如果它不作为管理员运行

有时忘记将其作为管理员运行。

如果脚本没有以管理员身份运行,是否可以停止脚本并显示消息框?

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

这检索当前的Windows标识,如果当前标识具有管理员角色返回True(即运行升高)。

从那里,你可以在一个if -not块包裹,并出示一个消息框,如下所示:

if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { 
    [System.Windows.Forms.Messagebox]::Show("Not running as administrator!"); 
} 

注:这是基于这个答案在这里:https://superuser.com/a/756696