I ended up having to resort to a commercial software package for this due to the difficulties Microsoft puts in the way of those who want their PowerShell scripts to run like batch files (double-click and it just runs)
My script:
- Needs to run as administrator
- …after being double-clicked, a UAC prompt is fine
- …regardless of the execution policy currently in place
The answer given above does work for making a script run as administrator, but the code required for doing so is both ugly, and doesn't address the execution policy problem (the script will just immediately fail). It also doesn't make the script double-clickable.
The other answer given will make the script double-clickable and have it run as administrator, but would be unsuitable for anything but a script that is being more or less "installed" on a system for regular use, and requires a lot of manual steps. It does not address the execution policy problem either, although it could since PowerShell is being invoked we could pass -executionpolicy bypass
as a option
There are other (free) tools out there that will "package" a PowerShell script into an EXE file like PS2EXE which neatly solved the double-clicking problem, but what I found is that this does not play well with the "run as admin" code given in the answer here, neither does it work around the execution policy.
I ended up going with PowerShell studio since it offers the same "packaging" ability that PS2EXE has, you can set a flag to force the EXE to run as admin (so no need for littering your script with escalation code), it executes the script with the bypass flag so you don't get stopped in your tracks or have to care what the local policy is set to, and perhaps most helpfully, has tools to "sign" the resulting package so that your user doesn't get scary warnings.
This is, so far, the only way I've found to reliably distribute a PowerShell script that requires admin permissions.
if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) -eq $false){Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass" -Verb RunAs; Exit;}
in your$Profile
- however, for some reason,Exit
does not work, therefore the original non-admin terminal will stay open... (you could also include that script in a slightly modified version in each script that need admin privileges.)