Reputation: 3
My Powershell script starts with the check if PS is running in elevated mode, if not it starts itself again in elevated mode. At my system it is running without problems. At another system the second shell starts and dies after a second. Does someone know this problem or could give me a hint how to trouble shoot. No anti virus is active and execution policy is set by group policy.
Here is the code (found somewhere on SO):
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Host "Running elevated..."
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
Upvotes: 0
Views: 236
Reputation: 5227
All you need to do is to add -noexit
parameter to your arguments. You can do it like this:
$arguments = "-noexit & '" + $myinvocation.mycommand.definition + "'"
It might also happen that you don't need $myinvocation.mycommand.definition
part (this would only execute the same command once again in new window so it's not quite necessary). In that case you can just use:
$arguments = "-noexit"
or remove the variable and use this parameter directly:
Start-Process powershell -Verb runAs -ArgumentList '-noexit'
Also, if you wanted to troubleshoot the initial code you had, you could use:
$arguments = "& '" + $myinvocation.mycommand.definition + "'; pause"
In case there's any error it'll be visible in your screen as pause
waits until you press Enter
.
As mentioned by Rohin Sidharth, -noexit
is not necessary so the command might be just like:
Start-Process powershell -Verb runAs
This doesn't apply to the situation when powershell.exe
is executed with command like that:
Start-Process powershell -Verb runAs -ArgumentList 'Write-Host "test"'
as it'll close the window after execution.
Upvotes: 0
Reputation: 2676
You don't need the arguments at all. This is enough.
Start-Process powershell -Verb runAs
Upvotes: 2