pandemic
pandemic

Reputation: 1195

Run PowerShell script as different user and hidden window from another PowerShell script

I need to run a PowerShell script from another PowerShell script as different user and hidden window.

What do I have so far:

Start-Process powershell '& C:\test.ps1' -WindowStyle Hidden -Credential $cred

where $cred is a PSCredential object. The test.ps1 script is for testing purposes one line with Remove-Item. As I can still see the file not being removed I can tell that the script is not being run.

EDIT

My original intention is to run regedit script but when I was implementing Start-Job answer (below) I've got this error:

Start-Job : The value of the FilePath parameter must be a Windows PowerShell script file. Enter th
e path to a file with a .ps1 file name extension and try the command again.

Upvotes: 0

Views: 913

Answers (2)

stalskal
stalskal

Reputation: 1347

You could use jobs for this. As the Powershell documentation says

A Windows PowerShell background job runs a command without interacting with the current session.

PS> $myJob = Start-Job -FilePath C:\test.ps1 -Credential $cred

To get the result/output of the job, use Receive-Job

PS> $myJob | Receive-Job -Keep

Upvotes: 1

Stormravenx
Stormravenx

Reputation: 11

You can run the PowerShell scripts through task scheduler. I'm not sure if it is your goal, but it will let you execute PowerShell scripts on a user's session using their credentials.

I'll let you Google the how to, to fit your needs.

Upvotes: 0

Related Questions