在 PowerShell 脚本中,如何检查我是否以管理员权限运行?
答案1
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
(从命令行安全技巧)
答案2
如果未以管理员身份运行,则导致脚本不运行:
#Requires -RunAsAdministrator
https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_requires
输出:
脚本“MyScript.ps1”无法运行,因为它包含以管理员身份运行的“#requires”语句。当前 Windows PowerShell 会话未以管理员身份运行。使用以管理员身份运行选项启动 Windows PowerShell,然后尝试再次运行该脚本。
在 PowerShell 4.0 中引入。
答案3
function Test-Administrator
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
执行上述函数。如果结果为 True,则用户具有管理员权限。
答案4
这将检查您是否是管理员,如果不是,则它将以管理员身份在 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
}