keyneom
keyneom

Reputation: 835

How can I run a command in PowerShell with admin rights in the current shell?

I attempted to write a short runas-admin function where I could pass another function name as a parameter and have that command executed with admin rights (more or less the equivalent of sudo in linux). When I try running the function it runs continuously and never ends, taking up a lot of cpu. I'm new to PowerShell, so is there something wrong with my code?

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();
}
}

Upvotes: 0

Views: 3052

Answers (1)

Keith Hill
Keith Hill

Reputation: 201612

Or you could just run Start-Process with the verb runas e.g.:

Start-Process powershell.exe -Verb runas

Upvotes: 1

Related Questions