Invoke-RunAsLoggedOnUser
Description
Section titled “Description”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.
Syntax
Section titled “Syntax”Invoke-RunAsLoggedOnUser -command <string> -username <string> -arguments <string>
Parameters
Section titled “Parameters”command (String)
Section titled “command (String)”Mandatory. The command/executable to run. Example: "C:\Program Files\PowerShell\7\pwsh.exe".
username (String)
Section titled “username (String)”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.
arguments (String)
Section titled “arguments (String)”Optional. Arguments passed to command. Default is $null.
Return value
Section titled “Return value”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.
Considerations
Section titled “Considerations”- The scheduled task waits up to 30 minutes for
commandto finish before giving up; the task is unregistered afterwards either way. - Because
Invoke-RunAsLoggedOnUserruns the command asynchronously via Task Scheduler, its return value only reflects whether the task itself could be created and run — not the exit code ofcommandinside the user session.
Example
Section titled “Example”Invoke-RunAsLoggedOnUser -command 'mkdir' -arguments 'C:\Temp'Invoke-RunAsLoggedOnUser -command 'mkdir' -arguments 'C:\Users\test\Documents' -username 'domain\username'$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