I've taken the liberty of quickly building this as a standalone function. I haven't tested it but you might want to try it out and see if you can fix it up anywhere it needs work. You can then release it as an extension, as it could be really useful to others :) This will use the in-built toolkit functions so you get full logging throughout.
Function Execute-ProcessAsUser {
Param(
[string] $FilePath = $(Throw "Command Param required"),
[string] $Arguments = $null
)
# If the file is in the Files subdirectory of the App Deploy Toolkit, set the full path to the file
If (Test-Path (Join-Path $dirFiles $FilePath -ErrorAction SilentlyContinue) -ErrorAction SilentlyContinue) {
$FilePath = (Join-Path $dirFiles $FilePath)
}
# Only launch app if an actual user is logged on
If ($envUsername -ne $null -and $envUsername -ne "SYSTEM") {
Write-Log "Executing [$FilePath $Arguments] in user context using Scheduled Tasks..."
# Create Scheduled Task to run Jabber in logged on user context
Execute-Process -FilePath "schtasks.exe" -ArgumentList "/create /f /ru '"$envUsername'" /sc once /sd '"01/01/1980'" /ST '"00:00:00'" /tn PSAppDeployToolkitExecuteAsUser /tr '"\'"$FilePath\'" $Arguments" -Wait -WindowStyle Hidden
# Trigger Scheduled Task
Execute-Process -FilePath "schtasks.exe" -ArgumentList "/run /i /tn PSAppDeployToolkitExecuteAsUser" -Wait -WindowStyle Hidden
# Delete Scheduled Task
Execute-Process -FilePath "schtasks.exe" -ArgumentList "/delete /tn PSAppDeployToolkitExecuteAsUser /f" -Wait -WindowStyle Hidden
Else {
Write-Log "No user is logged in. Skipping execution of: [$FilePath $Arguments]"
}
}