Create scheduled task to run at user log-on as user him/herself

Hi everyone

We sometimes have a requirement to replicate the behaviour of GPOs that run in the user context. This means you need to execute a task under the current logged on user and trigger it to occur only when user logs on.

To achieve this, we can use a scheduled task with 2 special settings:

  1. It is triggered only when a user logs on
  2. It runs under the context of the local “USERS” group.

With #2, you are able to access all the usual user-context-specific data such as %USERNAME%, HKCU, etc. And, this approach makes the scheduled task run under the context of ANY user that logs on. Say for example you have 2 users - USERA and USERB logging on, the scheduled task will take on the security context of USERA or USERB depending on who logs on.

Unfortunately, you cannot achieve this with the New-ScheduledTask cmdlet. You will have to use COM programming. Here’s the code:

$ShedService = New-Object –comobject 'Schedule.Service'
$ShedService.Connect()

$Task = $ShedService.NewTask(0)
$Task.RegistrationInfo.Description = "Test Task - Runs when user logs on, and under user's context"
$Task.Settings.Enabled = $true
$Task.Settings.AllowDemandStart = $true

$trigger = $task.triggers.Create(9)
$trigger.Enabled = $true

$action = $Task.Actions.Create(0)
$action.Path = "cmd.exe"
$action.Arguments = "/c echo %temp% > c:\temp\out.txt"

$taskFolder = $ShedService.GetFolder("\")
$taskFolder.RegisterTaskDefinition("Run at user logon", $Task , 6, "Users", $null, 4)

You can examine the file “c:\temp\out.txt” and see that the text in there points to the temporary folder of the user who just logged on.

1 Like