Skip to content

Invoke-RunAsLoggedOnUser

Runs a single command in the context of the logged-on user, from a PowerPack script that otherwise runs as SYSTEM. It works by registering a hidden scheduled task (PowerPackUserJob) with an At log on trigger for the target user and starting it immediately, then waiting for it to finish before cleaning the task back up.

If no username is given, the logged-on user is auto-detected from the owner of the explorer.exe process. If more than one user is logged on (e.g. multiple concurrent sessions), the command is run once for each detected user.

Invoke-RunAsLoggedOnUser -command <string> -username <string> -arguments <string>

Mandatory. The command/executable to run. Example: "C:\Program Files\PowerShell\7\pwsh.exe".

Optional. The user to run as, e.g. 'domain\username'. If omitted, the currently logged-on user is auto-detected from the owner of explorer.exe. The target user must be physically logged on — nothing happens otherwise. Default is $null.

Optional. Arguments passed to command. Default is $null.

Int32. 0 on success (including the no-op case where no user is logged on), or the failing operation’s HResult if an unexpected error occurs while managing the scheduled task.

  • The scheduled task waits up to 30 minutes for command to finish before giving up; the task is unregistered afterwards either way.
  • Because Invoke-RunAsLoggedOnUser runs the command asynchronously via Task Scheduler, its return value only reflects whether the task itself could be created and run — not the exit code of command inside the user session.
Terminal window
Invoke-RunAsLoggedOnUser -command 'mkdir' -arguments 'C:\Temp'
Terminal window
Invoke-RunAsLoggedOnUser -command 'mkdir' -arguments 'C:\Users\test\Documents' -username 'domain\username'
Terminal window
$Command = "C:\Program Files\PowerShell\7\pwsh.exe"
$Arguments = "-Command `"Import-PfxCertificate -Password `$('$PlainTextPassword' | ConvertTo-SecureString -AsPlainText -Force) 'C:\Cert.p12' -CertStoreLocation Cert:\currentUser\My`""
Invoke-RunAsLoggedOnUser -command $Command -arguments $Arguments