1

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.

Jeff Fol
  • 1,400
  • 3
  • 18
  • 35
  • 4
    Do not store username and password in a script. Store the credentials in the scheduler, and specify the account you want to use. – Bill_Stewart Oct 10 '17 at 21:53

1 Answers1

2

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.

Abhi
  • 31
  • 3