Last active
December 14, 2020 13:00
-
-
Save nopslider/5020a2dbdd780cb5afd6 to your computer and use it in GitHub Desktop.
A small powershell script which implements runas functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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