If you don't need to interact with the user, but only run a program, then give this a try.
For testing, I commented out your transcript and had the task run cmd.exe and simply delay for a bit.
# This script runs as the SYSTEM account.
#$transcriptPath = Join-Path -Path $PSScriptRoot -ChildPath "OfficeResetActivation.log"
#Start-Transcript -Path $transcriptPath
try {
# Define the path to SaRacmd.exe
#$exePath = Join-Path -Path $PSScriptRoot -ChildPath "SaRacmd\SaRacmd.exe"
$exePath = "c:\windows\system32\cmd.exe"
# Look for an explorer process to insure that someone is logged on to the desktop
$timeout = 5 # how long do we wait for a user
$count = 0
$wait4user = $true
while ($wait4user) {
$count++ # how many times have we looped through this
if ($count -gt $timeout) {
throw "We have waited too long for a user to log on."
}
$e = Get-Process -Name Explorer -ErrorAction SilentlyContinue
if ($e.count -gt 0) {
$wait4user = $false
"We found an Explorer process, someone is logged on."
} else {
"Sleeping"
Start-Sleep -Seconds 60 # wait for a minute
}
}
"We have a user."
Get-WmiObject Win32_Process -f 'Name="explorer.exe"' |% getowner |% user
# Define the task name
$taskName = "ResetOfficeActivation"
# Delete it if it already exists
get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue | Unregister-ScheduledTask -Confirm:$false
# Create a scheduled task to run as the logged-in user
#$action = New-ScheduledTaskAction -Execute $exePath -Argument "-S ResetOfficeActivation -AcceptEula -CloseOffice"
$action = New-ScheduledTaskAction -Execute $exePath -Argument "/c timeout /t 30"
$principal = New-ScheduledTaskPrincipal -GroupId "Interactive"
# We don't need a trigger
$t = Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal -Force
# Start the task immediately
Start-ScheduledTask -TaskName $taskName
Write-Output "Scheduled task '$taskName' created and started."
Start-Sleep -Seconds 2 # give it a few seconds to fire up
$timeout = 20 # how many loops do we wait for the task to finish
$count = 0
$wait4user = $true
while ($wait4user) {
$count++ # how many times have we looped through this
if ($count -gt $timeout) {
throw "We have waited too long for the task to finish."
}
$t = Get-ScheduledTask -TaskName $taskName
$t.State
if ($t.State -eq "Ready") {
$wait4user = $false
"Our task has finished."
} else {
Start-Sleep -Seconds 5 # wait for a minute
}
}
$TaskInfo = Get-ScheduledTaskInfo -TaskName $taskName
"Last run time is {0}" -f $TaskInfo.LastRunTime
"Task finished at {0}" -f (get-date)
"Return code is {0}" -f $TaskInfo.LastTaskResult
} catch {
# Log any errors that occur during the process
Write-Error "An error occurred: $_"
} finally {
# Stop the transcript
#Stop-Transcript
}