Run script as other user elevated


I’ve been struggling with this one all day.

Basically I have a script I run on new servers I deploy that changes registry,settings,silent installs, etc. I first login manually and run this is the administrator then I have to login as the user the script creates and run it again because some settings are profile specific. So I run it twice which causes overlap which I don’t need.

My solution to that is I’m going to have the script check which user is running the script and only have it run the commands needed for that user, mainly the second user is the only one I have to run less commands on because the initial run takes care of a majority of it.

So now what I want to do is have a script that calls this script to run as the administrator first, which will work fine and it’ll run and do its thing. After it runs I want to call this script again and run it as another user HOWEVER it has to be elevated to do so, before we always ran powershell as administrator on the second account. But I need it to run as the second user so it can change those certain settings that are profile dependant.

IF someone has a better theory as to how to accomplish this I would appreciate it. Here is the script i’m testing with for running as another user elevated but its throwing an error in the new powershell and closes before i read it and I can’t figure out how to capture it.

$username = "test"
$password = "P@ssword123x"

$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

Start-Process powershell.exe -Credential $cred -ArgumentList “Start-Process param_pass_test.ps1 -arguementlist '-user 1' -Verb runAs 2>> results.txt” -WorkingDirectory $env:ALLUSERSPROFILE -Wait 2>> results.txt

There is a typo error on the 8th line. In the start-process argument lists.

Start-Process powershell.exe -Credential $cred -ArgumentList “Start-Process param_pass_test.ps1 -argumentlist '-user 1' -Verb runAs 2>> results.txt” -WorkingDirectory $env:ALLUSERSPROFILE -Wait 2>> results.txt

Make sure your param_pass_test.ps1 script is accepting the parameter ‘-user 1’.

Instead of using that much script to create a credential object, you can also use get-Credential cmdlet.