我的Powershell代码首先以用户身份运行,然后当用户要执行其他操作时,我想启动另一个脚本,但是该脚本需要管理员权限,因此我在第一个Powershell中有此命令以admin身份运行所需的脚本
Start-Process -WindowStyle Hidden -FilePath PowerShell.exe -Verb Runas -ArgumentList "-executionpolicy bypass -File $path"
但这只是什么都不做,甚至没有运行文件
答案 0 :(得分:0)
我写了一个关于您要做什么的函数
<#
.SYNOPSIS
Creates new powershell consoles
.DESCRIPTION
Used to create new powershell consoles running as same rights unless Elevated is selected in which case it runs as administrator
.EXAMPLE
New-PowershellConsole -Count 2 -Elevated -Exit
.PARAMETER Count
Starts up this many consoles
.PARAMETER Elevated
Starts Consoles as Administrator
.PARAMETER Exit
Closes the current powershell console
#>
function New-PowershellConsole {
param(
[int]$Count = 1,
[switch]$Elevated,
[switch]$Exit
)
if ($(new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) -or $($Elevated -eq $True)) {
while ($Count -gt 0){
Start-Process powershell -Verb runAs -ArgumentList "-NoExit -Command `"Set-Location $((Get-Location).path)`"";
$Count--
}
} else {
while ($Count -gt 0){
Start-Process powershell -ArgumentList "-NoExit -Command `"Set-Location $((Get-Location).path)`"";
$Count--
}
}
If($Exit){
exit
}
}
根据您的消息,您似乎想以管理员身份运行新的Powershell控制台
Start-Process powershell -Verb runAs -ArgumentList "-NoExit";
我建议避免错误是检查用户是否是管理员
if ($(new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) -or $($Elevated -eq $True)) {
Start-Process powershell -Verb runAs -ArgumentList "-NoExit";
}