Skip to content

Instantly share code, notes, and snippets.

@dfparker2002
Forked from nopslider/runas.ps1
Created June 28, 2018 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfparker2002/81cf7fd7946023783564c98e40e8e23f to your computer and use it in GitHub Desktop.
Save dfparker2002/81cf7fd7946023783564c98e40e8e23f to your computer and use it in GitHub Desktop.
A small powershell script which implements runas functionality
param($username, $password, $command, $arguments = " ")
# Don't use c:\windows\temp below, as standard users don't have access to it
$errfile = "c:\users\public\runas_error.txt"
$outfile = "c:\users\public\runas_out.txt"
$envusername = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
write-host "Supplied Username = " $username
write-host "Env Username = " $envusername
write-host "Password = " $password
write-host "Command = " $command
write-host "Arguments = " $arguments
write-host "Outfile = " $outfile
write-host "Errfile = " $errfile
$securepassword = ConvertTo-SecureString -String $password -AsPlainText -Force;
$creds = New-Object System.Management.Automation.PSCredential($username,$securepassword)
$myfile = $MyInvocation.MyCommand.Definition
# Works with local and domain users
if (($env:username -eq $username) -or ($envusername -eq $username)) {
#Run the actual command as the privileged user
Start-Process -FilePath $command -ArgumentList $arguments -RedirectStandardOut $outfile -RedirectStandardError $errfile
#Exit, or you'll have a loop
exit
}
#We're not running as our intended user, respawn this script with creds
Start-Process powershell -ArgumentList "-ExecutionPolicy Bypass -File `"$myfile`" $username `"$password`" `"$command`" `"$arguments`"" -Credential $creds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment