# Invoke-RunAsLoggedOnUser

> Runs a single command in the context of the logged-on user, from a PowerPack script that otherwise runs as SYSTEM.

Source: https://docs.capaone.com/capainstaller/powerpacks/invoke-runasloggedonuser/  
Product: CapaInstaller — a separate CapaSystems product; do not apply this page to any other.

### 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.

:::caution
If no user is logged on — or the specified user isn't logged on — nothing happens: the function logs that fact and returns `0` without running the command.
:::

### Syntax

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

### Parameters

#### command (String)

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

#### 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)

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

### 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

- 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.

### Example

**PowerShell**

```powershell
Invoke-RunAsLoggedOnUser -command 'mkdir' -arguments 'C:\Temp'
```

```powershell
Invoke-RunAsLoggedOnUser -command 'mkdir' -arguments 'C:\Users\test\Documents' -username 'domain\username'
```

```powershell
$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
```
