Update: I updated the code below so it works correctly when there are spaces in the path or script name. Thanks to Pat Richard for performance and deprecation improvements.
Most of the scripts I write require elevation -- they must be run from an elevated PowerShell prompt because they make changes to Windows that require Administrator access. The following code snippet will self-elevate a PowerShell script with this added to the beginning of the script. I honestly can't remember where I found the original code, but I updated it to work with Windows 10 and Windows Server 2016 and later build numbers.
Of course, you should ALWAYS confirm that your script is running properly before allowing it to self-elevate. I take no responsibility for the scripts that run using this code.
Simply add this snippet at the beginning of a script that requires elevation to run properly. It works by starting a new elevated PowerShell window and then re-executes the script in this new window, if necessary. If U