当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何检查PowerShell脚本是否以管理员身份运行?

作者:精品下载站 日期:2024-12-14 20:07:58 浏览:17 分类:玩电脑

如何检查PowerShell脚本是否以管理员身份运行?


如果您需要以管理员权限运行PowerShell脚本,您可以在PS代码中检查当前的powershell.exe进程是否具有提升的权限。

以下PowerShell代码可用于检查当前脚本是否以“以管理员身份运行”模式运行:

Write-Host "Checking for elevated permissions..."
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "Insufficient permissions to run this script. Open the PowerShell console as an administrator and run this script again."
Break
}
else {
Write-Host "Code is running as administrator — go on executing the script..." -ForegroundColor Green
}

[玩转系统] 如何检查PowerShell脚本是否以管理员身份运行?

将 PowerShell 代码保存到 check_process_elevation.ps1 文件中,并在控制台中运行,无需管理员权限:

C:\PS\check_process_elevation.ps1

如您所见,出现消息表明您没有管理员权限,因此 PowerShell 脚本已停止。

[玩转系统] 如何检查PowerShell脚本是否以管理员身份运行?

现在在提升的 PowerShell 会话中运行该脚本。如您所见,脚本已检测到此 PowerShell 会话以管理员身份运行。

[玩转系统] 如何检查PowerShell脚本是否以管理员身份运行?

您还可以直接从 PowerShell 脚本请求提升。要做到这一点,而不是字符串:

Write-Warning "Insufficient permissions…”

使用以下代码:

Start-Process Powershell -ArgumentList $PSCommandPath -Verb RunAs

在没有管理员权限的情况下运行脚本时,它将在新的提升的 PowerShell 会话中重新运行,并且您将看到 UAC 提升提示。如果您接受,您的 PS1 脚本将以管理员身份运行。 (使用以下命令传输 PowerShell 脚本当前文件的路径

$PSCommandPath

环境变量。)

[玩转系统] 如何检查PowerShell脚本是否以管理员身份运行?

在 PowerShell 4.0 或更高版本中,检查脚本是否以管理员权限运行更加容易。为此,请使用 -RunAsAdministrator 指令。

#requires -version 4.0
#requires -RunAsAdministrator
Write-Host "PowerShell is run as administrator" -ForegroundColor Green

如果脚本不是在管理员下运行,会出现如下错误:

The script ‘check_process_elevation.ps1’ cannot be run because it contains a “#requires” statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.
At line:1 char:1
+ C:\PS\check_process_elevation.ps1
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (check_process_elevation.ps1:String) [], ScriptRequiresException
+ FullyQualifiedErrorId : ScriptRequiresElevation

[玩转系统] 如何检查PowerShell脚本是否以管理员身份运行?

如果您在使用 PowerShell v2 的计算机上运行该脚本,将出现以下错误消息:

Cannot process the “#requires” statement at line 2 because it is not in the correct format.
The “#requires” statement must be in one of the following formats:
“#requires -shellid <shellID>”
“#requires -version <major.minor>”
“#requires -pssnapin <psSnapInName> [-version <major.minor>]”

要管理 Active Directory,您可能需要执行另一项任务:通过 PowerShell 脚本检查当前用户是否具有域管理员权限。使用以下代码:

If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole("Domain Admins"))
{
#a user running the script has the Domain Admins rights
}
Else
{
#no Domain Admins rights
}

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯