我发现了一个关于这个主题的老问题。不过,我并不清楚。 我有一个脚本,用于检查 PS 是否已使用“以管理员身份运行”运行,如果是,则它会执行该作业,否则它会提示该脚本必须以管理员身份运行。
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CheckforAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
它给出 true 或 false。我有 if-else 语句来完成剩下的工作。
If($CheckforAdmin -eq 'True'){
$MSG = ""
If(($EventLogCheck -ne $EventLog) -or ($EventLogsourceCheck -ne 'True')){
New-EventLog -LogName $EventLog -Source $EventLogSource -ErrorAction Stop
$MSG = "$env:USERNAME has successfully created a new eventlog named $EventLog with the source $EventLogSource."
Write-EventLog -logname $PiEventLog -source $PiEventLogSource -eventID 1021 -entrytype Information -message $MSG
}
else{
$MSG = "$env:USERNAME tried to create an EventLog named $EventLog with the source $EventLogSource. `nSince the EventLog and the source already exist, this step was aborted."
Write-EventLog -logname $EventLog -source $EventLogSource -eventID 1021 -entrytype Information -message $MSG
}
# Wenn der Parameter Silent auf true gesetzt ist, wird das Skript nach der Erstellung des EventLogs unmittelbar beendet.
if($install -eq $true){
Write-Host $MSG
Read-Host 'Press any key to continue...'
}
exit
}
else{
Write-Host "The Script must be executed as admin"
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
[System.Windows.Forms.MessageBox]::Show('Installation: The script must be run as administrator in order to create the event log', 'Run as admin')
exit
}
如果我使用普通用户登录,它效果很好。但是在我想运行脚本的服务器上,我以域管理员身份登录。即使运行脚本只是双击它,它也会运行,而不是提示必须使用“以管理员身份运行”来运行脚本。
我红色了有关UAC(用户帐户控制)的文章,据我了解:使用“以管理员身份运行”运行脚本实际上与以域管理员身份登录并双击脚本相同。
是否有其他方法可以检查脚本是否使用“以管理员身份运行”选项运行,如果您右键单击 powershell,则会显示该选项(没关系,无论您是否以管理员身份登录)?
在脚本顶部添加以下行:
#Requires -RunAsAdministrator
然后删除所有代码以检查管理员。
如果运行脚本的用户不是高级管理员,则会显示一条消息,并且脚本的执行将停止。
原评论:
你是如何实现这个提示的?因为显然,这部分只返回 $true 或 $false。我想解决这个问题的方法是这样的
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""PS_Script_Path&Name.ps1""' -Verb RunAs}"
再次以管理员身份调用脚本(如果之前不是的话)。
新增:
此外,您的 if 语句中有错误。为了与布尔值进行比较,您希望 if 语句如下所示:
If($CheckforAdmin -eq $true){
与字符串进行比较可能会导致问题。否则我找不到任何其他错误。
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
管理员PowerShell: 返回真
非管理员 PowerShell: 返回错误
默认情况下,Admin PowerShell 始终为我运行: 返回真