How to elevate a PowerShell script automatically.
Add this before your PowerShell script commands to ensure they run with elevated permissions and retain the current working directory.
This command will start PowerShell with elevations and retain working directory to continue whatever commands you put after it, that way you can simply right-click and choose run with PowerShell... just like the good old run as administrator for batch files.
Here's the script:
#================================================================================
#runs PowerShell as admin and also preserves working directory
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
# Your remaining script goes here
Ещё видео!