Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restart powershell with admin rights and continue with current script

Tags:

powershell

i am trying to check if powershell has admin rights. That is pretty simple and works fine but my problem is that powershell doesn't continue in the new instance with the script after it opens the new instance. The new instance runs in System32.

The new instance just shows: PS C:\windows\system32>

Is it also possible to close the first instance that is running after the second instance started?

function checkRights {
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$princ = New-Object System.Security.Principal.WindowsPrincipal($identity)
    if(!$princ.IsInRole( `
    [System.Security.Principal.WindowsBuiltInRole]::Administrator))
   {
     $powershell = [System.Diagnostics.Process]::GetCurrentProcess()
     $psi = New-Object System.Diagnostics.ProcessStartInfo $powerShell.Path
     $installPath = $MyInvocation.MyCommand.Path
     $script = $installPath
     $prm = $script
   foreach($a in $args) {
      $prm += ' ' + $a
   }
      $psi.Arguments = $prm
      $psi.Verb = "runas"
  [System.Diagnostics.Process]::Start($psi) | Out-Null
   return;
  }
}
like image 280
MRoth Avatar asked Sep 03 '25 17:09

MRoth


1 Answers

This snippet runs the same script in the new powershell process and exits the older shell.Script scoping was necessary for myinvocation (when called from a funcion) and added an exit function call :-) :

     function checkRights() {
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$princ = New-Object System.Security.Principal.WindowsPrincipal($identity)
    if(!$princ.IsInRole( `
    [System.Security.Principal.WindowsBuiltInRole]::Administrator))
   {
     $powershell = [System.Diagnostics.Process]::GetCurrentProcess()
     $psi = New-Object System.Diagnostics.ProcessStartInfo $powerShell.Path
      $psi.Arguments = '-file ' + $script:MyInvocation.MyCommand.Path
      $psi.Verb = "runas"
  [System.Diagnostics.Process]::Start($psi) | Out-Null
   return $false
  }
  else{
  return $true
  }
}
$rights = checkrights
$rights
if($rights){
"opened in admin rights"
#for pausing
Read-Host

}else
{
"no admin rights ,trying to open in admin rights"
[Environment]::Exit(0)
}
like image 196
ClumsyPuffin Avatar answered Sep 08 '25 02:09

ClumsyPuffin