我尝试编写一个简短的runas-admin函数,我可以将另一个函数名作为参数传递,并使用admin权限执行该命令(或多或少相当于linux中的sudo)。当我尝试运行该函数时,它会持续运行并且永远不会结束,占用了大量的cpu。我是PowerShell的新手,所以我的代码有问题吗?
function runas-admin
{
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$newProcess.RedirectStandardError = $TRUE;
$newProcess.RedirectStandardOutput = $TRUE;
$newProcess.UseShellExecute = $FALSE;
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
$childProcess = [System.Diagnostics.Process]::Start($newProcess);
$childProcess.WaitForExit();
Write-Output $childProcess.StandardOutput.ReadToEnd();
}
}
答案 0 :(得分:1)
或者您可以使用动词Start-Process
运行runas
,例如:
Start-Process powershell.exe -Verb runas