我有一些我们需要部署软件的计算机系统 . 我一直在使用一种简单的方法来检测用户是否是本地管理员,然后检测他们是否具有管理员权限 . 如果需要,脚本将使用提升的权限重新启动 . 如果用户不是本地管理员,则脚本将使用其他凭据(本地管理员)重新启动 . 该脚本适用于具有更高版本PowerShell的系统,如Windows 8和Windows 10 .
问题是当用户不是管理员且脚本在Windows 7上运行时 . 脚本使用 $PSScriptPath 重新启动脚本 . 我不认为这在早期版本的PowerShell中有效 . 所以如果主要的PowerShell版本是<3,我尝试自己设置 $PSScriptRoot . 然后问题是脚本卡在某种循环中,它只是不断打开和关闭窗口然后我必须杀死它...如果我不喜欢定义 $PSScriptRoot 我收到错误
无法将参数绑定到参数'Path',因为它为null
我假设这是因为在PowerShell 2.0中没有定义 $PSScriptRoot .
这是我正在尝试做的一个例子:
#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
}