【发布时间】:2016-10-12 12:40:57
【问题描述】:
我有很多计算机系统需要我们部署软件。我一直在使用一种简单的方法来检测用户是否是本地管理员,然后检测他们是否具有管理员权限。如果需要,脚本会以提升的权限重新启动。如果用户不是本地管理员,则脚本会使用不同的凭据(本地管理员)重新启动。该脚本适用于具有更高版本 PowerShell(例如 Windows 8 和 Windows 10)的系统。
问题是当用户不是管理员并且脚本在 Windows 7 上运行时。脚本使用$PSScriptPath 重新启动脚本。我认为这在早期版本的 PowerShell 中不起作用。因此,如果主要 PowerShell 版本 $PSScriptRoot。问题是脚本陷入某种循环,它只是不断打开和关闭窗口,然后我必须杀死它......如果我没有定义$PSScriptRoot 我得到错误
无法将参数绑定到参数“路径”,因为它为空
我认为这是因为 $PSScriptRoot 未在 PowerShell 2.0 中定义。
这是我正在尝试做的一个示例:
#Check if PowerShell version is greater than 2. If not, set $PSSriptRoot.
if ($PSVersionTable.PSVersion.Major -lt 3) {
$PSScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
}
#Check if the user is a local admin. If they are, set $LocalAdmin to $True.
$LocalAdmin = $false
if ((net localgroup administrators) -match ([System.Environment]::UserDomainName + "\\" + [System.Environment]::Username)) {
$LocalAdmin = $true
}
if ($LocalAdmin) {
#Check if the local admin needs to run the script as administrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"
Start-Process powershell -Verb runas -ArgumentList $arguments
break
}
} else {
#Not a local admin. Relaunch script as admin user.
Start-Process -Credential $credential (Join-Path $PSHome powershell.exe) -ArgumentList (@("-File",
(Join-Path $PSScriptRoot $MyInvocation.MyCommand)) + $args)
exit
}
【问题讨论】: