Elevating a PowerShell script does not work in Windows 11

Erel A 1 Reputation point
2022-07-10T16:37:42.677+00:00

I am trying to make sure my script runs on elevated PowerShell.

For that, I am using the following snippet:

Verify whether running as Administrator

if (!(Test-Elevated)) {  
    # Stop, and run as Administrator  
    Write-Host 'Not running as Administrator, attempting to elevate...'  
    $arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"  
    Start-Process powershell.exe -Verb runAs -ArgumentList $arguments  
    Start-Sleep -Seconds 3  
    Stop-Process -Id $PID  
}  

I would like to kill the old process, then re-run it on a new, elevated PowerShell process.

This works using a Windows 10 PC, but while trying to run the same script on my Windows 11 Laptop, I get the UAC prompt, I accept, then for a quick second a new PowerShell process opens, and immediately close, without actually executing my script. It seems as if the $arguments are not being included as part of the Start-Process command.

What might be the reason, and solution to this problem?

Windows for business Windows Server User experience PowerShell
Windows for business Windows Client for IT Pros User experience Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. S.Sengupta 24,476 Reputation points MVP
    2022-07-11T00:56:25.367+00:00

    Do other scripts run fine ? or just problem with running your specific script only?


  2. Randy in Marin 6 Reputation points
    2023-02-01T18:03:05.7966667+00:00

    Was there a resolution? If the script is on a mapped drive, it will lose access to the mapped drive and close. I'm worried that there's a new security feature in Windows 11 that prevents the script from elevating. I don't want the effort to run an automation script to cost more than the script.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.