In Windows, can NT Authority/System run a powershell script as another user

Viewed 1285

I am running a powershell script remotely via an agent. The agent on the machine runs the powershell script as "NT Authority/SYSTEM" but I want to the switch to another user on the system and run the powershell script.

Below is the code that I used to switch to "Administrator" account but I am getting permission denied error .

$username = "domainname\administrator"
$pw = "XXXXXXXX"
$password = $pw | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
Start-Process Powershell.exe -Credential $cred  -ArgumentList '-noexit','-File', ' C:\Users\Administrator\test.ps1'

Below is the error I am getting. 
 Start-Process : This command cannot be run due to the error: Access is denied.
2 Answers

Try using invoke-command like below

$remoteSession=New-PSSession RemoteComputername -credential $credential1
Invoke-Command -session $remoteSession -scriptblock {
$newcredential = New-Object System.Management.Automation.PsCredential("domain\myuser", (ConvertTo-SecureString "password" -AsPlainText -Force))
Start-Process powershell.exe -Credential $newcredential ArgumentList '-noexit','-File', ' C:\Users\Administrator\test.ps1'
}

References:
https://community.idera.com/database-tools/powershell/ask_the_experts/f/powershell_remoting-24/14483/runas-a-different-user-on-a-remote-server

I had the exact same issue while trying to launch a powershell script on my Windows 10 guest from a Linux host, through qemu-guest-agent.

Part of what my script did was launching a desktop software and interacting with its gui.

My problem was solved using PsExec.

My agent command :

virsh -c qemu:///system qemu-agent-command my_domain \
'{"execute": "guest-exec", "arguments": { "path": "cmd.exe", "arg": [ "/c", "c:\\path\\to\\my_psexec_script.cmd" ], "capture-output": true }}'

My PsExec script, in the cmd file :

C:\path\to\PsExec.exe -accepteula \\DESKTOP-NAME -u user -p password -i sessionid powershell.exe -File C:\path\to\powershell_script.ps1

This is not a secure solution since the password is stored within the script.

To get the session id of the user of your choice, use the following command :

query session

The reason I used an intermediary script to launch PsExec was simply because it was easier to do so on my guest rather than entering all the arguments from my agent.

I based my solution on this post

It was also important that my script executed in the foreground.

Related