简体   繁体   中英

PowerShell script running as different user in Windows Task Scheduler

I am trying to configure a PowerShell script which will run in Windows Task Scheduler for multiple service accounts. I found a way to run the PowerShell script with a given user via the 2nd answer in this link Running PowerShell as another user, and launching a script .

For reference this is the PowerShell snippet:

$username = 'userA'
$password = 'passwordA'

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process C:\BatchPath\MyBatch.bat -Credential $credential

Now in Windows Task Scheduler I configure the job and in the execution I have it setup to run Powershell.exe with additional arguments '-ExecutionPolicy Bypass C:\\ScriptPath\\Script.ps1'. If the user for this task scheduler entry is configured as userA then it works. If I configure the task scheduler entry on userB then it fails. Both userA and userB are administrators on the machine.

In the second scenario I would expect that the script file would be started by userB but then the PowerShell Start-Process would force the batch file to be run as userA. From watching Task Manager I don't see the job within the batch file started.

This example is a bit superficial but in the final form of the PowerShell script it would be running different batch files with different service accounts.

This issue is because the Powershell window once opened with 'UserA' will only run the internal processes or any other subordinate tasks with 'UserA' creds from the task-scheduler. Even if you -force it to run with 'UserB' creds just the same as in your case, it wouldn't take it.

You'll need to create a jump task to run the process with 'UserB' creds.

Consider this, 1) create a task *TaskA with *UserA creds in the task scheduler, which creates another task *TaskB with *UserB creds in the scheduler using (Register-ScheduledTask). 2) Now, when you execute *TaskA from the scheduler, it'll create *TaskB in the scheduler. 3) Finally, if you run the *TaskB, it'll run the process with *UserB creds.

I hope this sorts your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM