Use PowerShell to Run an Application as the Current Logged In User

This blog explains how we can use PowerShell to run an application as the current logged in user.

There are times, for example when deploying an application or a script via SCCM, that the launching process will run as a SYSTEM account but we need to spawn a process in the context of the logged in user instead.

Some people suggest using something like:

Start-Process notepad.exe -Credential "username"

But this wont work since it prompts for credentials, and we want this to be automated.

The easiest option is to use a scheduled task. You might want to read our blog on how to create a scheduled task using PowerShell. In this example, we’ll simply try to launch notepad.exe as the logged in user.

If we simply set a scheduled task action of:

notepad.exe

The scheduled task will be stuck in a ‘running’ state until we close the notepad.exe process. So instead, we want to “launch and forget” by using cmd.exe with START like so:

c:\windows\system32\cmd.exe /c START "" notepad.exe

There are several other configurations that we need to specify in our final script. For example, we specify that the time it will take to launch our exe will be up to a minute (hopefully much less!), and the scheduled task will auto-delete after this period of time too.

#we want to launch and forget, so delete the task after a minute
$timeToExecuteInMins = 1
#get the logged in user
$principal = New-ScheduledTaskPrincipal -UserId (Get-CimInstance –ClassName Win32_ComputerSystem | Select-Object -expand UserName)
#create a one-time executing trigger
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date)
#required to set DeleteExpiredTaskAfter
$trigger.StartBoundary = (Get-Date).ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.EndBoundary = (Get-Date).AddMinutes($timeToExecuteInMins).ToString("yyyy-MM-dd'T'HH:mm:ss")
#configure other settings, such as auto deleting after 1 minute
$settings = New-ScheduledTaskSettingsSet –AllowStartIfOnBatteries -Hidden –DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes $timeToExecuteInMins) -DeleteExpiredTaskAfter (New-TimeSpan -Minutes $timeToExecuteInMins)
#define our action to launch notepad.exe and 'forget'
$action = New-ScheduledTaskAction -Execute "C:\windows\system32\cmd.exe" -Argument "/c START """" notepad.exe"
#give our task a unique name in case it runs multiple times in succession
$timeInSeconds = [DateTimeOffset]::Now.ToUnixTimeSeconds()
$taskName = "AlkaneTask-$timeInSeconds"
$task = New-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "Alkane scheduled task"
try {
Register-ScheduledTask $taskName -InputObject $task -Force -ErrorAction Stop | Out-Null
#start the scheduled task
Start-ScheduledTask -TaskName $taskName  -ErrorAction Stop | Out-Null
} catch {
write-host $_
}

The easiest way to check is to look in the username column of the details tab in task manager for the process you are launching.

It’s an extremely useful example of how we can use PowerShell to run an application as the current logged in user.

Create a Scheduled Task using PowerShell or Schtasks

In this blog we provide an example of how we can create a scheduled task using PowerShell or Schtasks.

Create a Scheduled Tasking using PowerShell

As a minimum, a scheduled task needs an action (something to perform) and a trigger (when to perform it). We can define a scheduled task that launches msedge.exe with an argument of https://www.alkanesolutions.co.uk at 3pm every day like so (you may need to elevate your code, depending upon the triggers and actions that you specify):

$trigger = New-ScheduledTaskTrigger -Daily -At 3:00PM
$action = New-ScheduledTaskAction -Execute "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" -Argument "https://www.alkanesolutions.co.uk"
Register-ScheduledTask -TaskName "AlkaneTask" -Trigger $trigger -Action $action -Description "Alkane scheduled task"

But as we know, there are various other configurations that we might want to customise such as execution time limits, whether it is hidden, or whether we want it to run if only powered by batteries and so on. We can adapt our simple scheduled task using PowerShell like so:

$trigger = New-ScheduledTaskTrigger -Daily -At 3:00PM
$action = New-ScheduledTaskAction -Execute "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" -Argument "https://www.alkanesolutions.co.uk"
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -Hidden -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
Register-ScheduledTask -TaskName "AlkaneTask" -Trigger $trigger -Action $action -Settings $settings -Description "Alkane scheduled task"

There are many more options to explore for each cmdlet. For example, we may want to add multiple triggers for our Scheduled Task using PowerShell:

$trigger1 = New-ScheduledTaskTrigger -Daily -At 3:00PM
$trigger2 = New-ScheduledTaskTrigger -Daily -At 4:00PM
$action = New-ScheduledTaskAction - -Execute "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" -Argument "https://www.alkanesolutions.co.uk"
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -Hidden -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
Register-ScheduledTask -TaskName "AlkaneTask" -Trigger @($trigger1,$trigger2) -Action $action -Settings $settings -Description "Alkane scheduled task"

Create a Scheduled Tasking using PowerShell and Schtasks.exe

Sometimes, coding a scheduled task using PowerShell can seem fiddly. Especially if you’re an inexperienced scripter. So another option is to manually create the scheduled task interactively, then export the scheduled task to an XML file and create the scheduled task using Schtasks.exe!

Open Task Scheduler (you can search for taskschd.msc if you need to). Right-click the Task Scheduler Library and create your scheduled task with all relevant configurations.

Once done, right-click your scheduled task and click Export. Then save it as an XML file (we’ll save it to a file called C:\Alkane\SchedTask.xml ). Then we can simply run the following to create our scheduled task using schtasks:

#create scheduled task
$returnmessage = (schtasks /Create /TN "AlkaneTask" /XML "C:\Alkane\SchedTask.xml")
write-host $returnmessage

and run the following to delete our scheduled task using schtasks:

$returnmessage = (SCHTASKS /Delete /TN "AlkaneTask" /F)
write-host $returnmessage

Whether we need to schedule routine maintenance scripts, backups, or any other task, PowerShell provides a powerful mechanism for automating these processes.