Skip to content

Instantly share code, notes, and snippets.

@nopslider
Last active December 14, 2020 13:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nopslider/5020a2dbdd780cb5afd6 to your computer and use it in GitHub Desktop.
Save nopslider/5020a2dbdd780cb5afd6 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
@tamih
Copy link

tamih commented Mar 22, 2018

Hi
I want to use your script to call an other .ps1 file (test.ps1) as administrator .
can you please give an example for the batch command that will use your code (as a file) and will make it run my file test.ps1.
thanks
Tami

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment