Function Enter-AdminSession {
<#
.SYNOPSIS
Self-elevate the script if required
.LINK
Source: https://stackoverflow.com/questions/60209449/how-to-elevate-a-powershell-script-from-within-a-script
#>
$scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value.Line
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
# we need to `cd` to keep the working directory the same ad before the elevation; -WorkingDirectory $PWD does not work
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList "cd $PWD; $scriptInvocation"
Exit
}
}
With this function in a common module that you imported or directly in your script, you can call Enter-AdminSession
at the right point in your script to gain admin rights.