0

我尝试编写一个简短的 runas-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();
}
}
4

1 回答 1

1

或者您可以只Start-Process使用动词,runas例如:

Start-Process powershell.exe -Verb runas
于 2012-12-16T01:02:42.977 回答