How to elevate an already running session within its own code

David Gidony picture David Gidony · Sep 3, 2015 · Viewed 8.5k times · Source

I'm writting a PowerShell script that configures some things in Active Directory.

I need to run it as a specific user in order to get the right permissions for the process, currently i'm running the .ps1 file through a .bat file, so I can choose "run as a different user" or "run as administrator".

What I'm tryng to achieve is that inside the script I will ask the user for the right credentials, and then elevate the session to run with the inputed user creds.

I've tried using this within my code:

Start-Process powershell.exe -Credential "TestDomain\Me"

But it just opens an empty PS Session while the current session keeps running.

I want to use this code to get the creds from the user:

$msg = "Enter your Domain Admin Credentials"; 
$creds = $Host.UI.PromptForCredential($caption,$msg,"","")
$rstusername = $creds.username;    
$rstpassword = $creds.GetNetworkCredential().password 

and then use $rstusername AND $rstpassword, to change the running script credentials.

Is that even possible?

Answer

Ansgar Wiechers picture Ansgar Wiechers · Sep 3, 2015

You can run cmdlets in another user's context when they allow providing explicit credentials (parameter -Credential), or by running them via Invoke-Command (which has a -Credential parameter).

Example:

$cred = Get-Credential
Invoke-Command -Computer $env:COMPUTERNAME -ScriptBlock {
  # commands here
} -Credential $cred

Or you could use something like this to re-run the entire script with different credentials:

if (-not $env:USERNAME -eq 'Me') {
  $cred  = Get-Credential
  $param = '-NoLogo', '-File', $MyInvocation.MyCommand.Path
  Start-Process "powershell.exe" -ArgumentList $param -Credential $cred
  exit $LASTEXITCODE
}

# other code here

Elevating the current session (or "moving" it to a different context) is not possible.