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;
}
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With