79707222

Date: 2025-07-19 12:13:33
Score: 0.5
Natty:
Report link
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.

Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: István Siroki