0

Putting this code in a PowerShell script makes it self-elevating:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
        [Security.Principal.WindowsBuiltInRole] 'Administrator'))
    {
        Start-Process PowerShell -ArgumentList "-File", ('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
        exit
    }

#Main code here

However, when making a function of it to use in PS user profile, and calling the function from a script, it does not work. A new PowerShell admin session is opened, but the main script code is not read.

function Elevate-NoAdmin
{
    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
        [Security.Principal.WindowsBuiltInRole] 'Administrator'))
    {
        Start-Process PowerShell -ArgumentList "-File", ('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
        exit
    }
}

Any ideas why it does not work as a function and if one can make it work?

2
  • 1
    code in your profile is in your profile script. it aint in your other script ... so you likely have a scope problem.
    – Lee_Dailey
    Mar 17, 2021 at 21:46
  • You can't wrap your code in a function like this, never put actual variables with values inside functions, functions accept inputted parameters and process them and output the result. Mar 18, 2021 at 5:48

1 Answer 1

0

Rewrote the function by defining a parameter that facilitates passing of the script path as a variable to the function in PS user profile. Otherwise it will use the path of the PS user profile instead.

function Elevate-NoAdmin
{
    param(
    [Parameter(Mandatory)]
    [String]$ScriptPath
    )
    
    if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::
        GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator'))
    {
        Start-Process -FilePath PowerShell.exe -Args "-File `"$ScriptPath`"" -Verb RunAs
        exit
    }
}

In script:

Elevate-NoAdmin $PSCommandPath

#Main code here

or

Elevate-NoAdmin $MyInvocation.MyCommand.Path

#Main code here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .