0

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.
1
  • Because the question is so common, I would point out that a PSCredential object for a user that's a member of Administrators won't run elevated using this technique. You would have to use the Runas verb for that. (I don't know whether that's your intention or not.) Commented Aug 7, 2017 at 16:23

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

tried your solution and it works perfectly with powershell scripts but not with regedit script. thought that it would be the same, damn powershell...
The file c:\test.ps1should contain regedit.exe /s c:\file.reg, or you could pass a scriptblock to Start-Job like so: Start-Job -ScriptBlock {regedit /s c:\file.reg} -Credential $cred
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.