![在 PowerShell 脚本中,如何检查我是否以管理员权限运行?](https://linux22.com/image/501423/%E5%9C%A8%20PowerShell%20%E8%84%9A%E6%9C%AC%E4%B8%AD%EF%BC%8C%E5%A6%82%E4%BD%95%E6%A3%80%E6%9F%A5%E6%88%91%E6%98%AF%E5%90%A6%E4%BB%A5%E7%AE%A1%E7%90%86%E5%91%98%E6%9D%83%E9%99%90%E8%BF%90%E8%A1%8C%EF%BC%9F.png)
在 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
}