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 executable to run. Example: "C:\Program Files\PowerShell\7\pwsh.exe". Built-in commands of the command prompt, such as mkdir, aren’t executables — run them through cmd.exe /c.

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 when the function completes, including the no-op case where no user is logged on.

  • The scheduled task runs with the highest privileges available to the user. If the user is a local administrator, the command runs elevated.
  • 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 'cmd.exe' -arguments '/c mkdir C:\Temp'
Terminal window
Invoke-RunAsLoggedOnUser -command 'cmd.exe' -arguments '/c mkdir C:\Users\test\Documents\Reports' -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