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 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.
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 when the function completes, including the no-op case where no user is logged on.
Considerations
Section titled “Considerations”- 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
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 'cmd.exe' -arguments '/c mkdir C:\Temp'Invoke-RunAsLoggedOnUser -command 'cmd.exe' -arguments '/c mkdir C:\Users\test\Documents\Reports' -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