0

別の関数名をパラメーターとして渡して、そのコマンドを管理者権限(Linuxのsudoとほぼ同等)で実行できる短いrunas-admin関数を作成しようとしました。関数を実行しようとすると、関数は継続的に実行され、終了することはなく、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 に答える