Answers:
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
(来自命令行安全提示)
在PowerShell中4.0你可以使用需要在你的脚本的顶部:
#Requires -RunAsAdministrator
输出:
无法运行脚本“ MyScript.ps1”,因为它包含一个“ #requires”语句以管理员身份运行。当前的Windows PowerShell会话未以管理员身份运行。使用“以管理员身份运行”选项启动Windows PowerShell,然后尝试再次运行脚本。
function Test-Administrator
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
执行以上功能。如果结果为True,则该用户具有管理员权限。
这将检查您是否是管理员,如果不是,则它将以管理员身份在PowerShell ISE中重新打开。
希望这可以帮助!
$ver = $host | select version
if ($ver.Version.Major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"}
# Verify that user running script is an administrator
$IsAdmin=[Security.Principal.WindowsIdentity]::GetCurrent()
If ((New-Object Security.Principal.WindowsPrincipal $IsAdmin).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) -eq $FALSE)
{
"`nERROR: You are NOT a local administrator. Run this script after logging on with a local administrator account."
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell_ise";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
作为上述答案的组合,您可以在脚本开头使用类似以下的内容:
# todo: put this in a dedicated file for reuse and dot-source the file
function Test-Administrator
{
[OutputType([bool])]
param()
process {
[Security.Principal.WindowsPrincipal]$user = [Security.Principal.WindowsIdentity]::GetCurrent();
return $user.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator);
}
}
if(-not (Test-Administrator))
{
# TODO: define proper exit codes for the given errors
Write-Error "This script must be executed as Administrator.";
exit 1;
}
$ErrorActionPreference = "Stop";
# do something
另一种方法是用此行启动脚本,这将在不以管理员权限启动时阻止其执行。
#Requires -RunAsAdministrator