2

I'm working on a PowerShell script that provides console output and restarts the system several times during the script's operation. As soon as it starts, it registers itself as a Scheduled Job so that it can pick up where it left off after restarts:

$JobArgs = @(
    $ScriptPath
    ($ArgumentList -join ' ')
)

$JobScript = {
    param(
        [string] $ScriptPath,
        [string] $Arguments
    )

    $PSArgs = @(
        '-NoExit'
        '-NoLogo'
        '-NoProfile'
        "-File $ScriptPath $Arguments"
    )

    Start-Process powershell.exe -ArgumentList $PSArgs -Wait
}

$AtLogonTrigger = New-JobTrigger -AtLogOn -User $LoginUser

$JobProperties = @{
    'Name'               = $JobName
    'Trigger'            = $AtLogonTrigger
    'ScheduledJobOption' = New-ScheduledJobOption -RunElevated
    'ScriptBlock'        = $JobScript
    'ArgumentList'       = $JobArgs
}

$Job = Register-ScheduledJob @JobProperties -ErrorAction Stop

However, while this does do what I want, it does so in the background when I would prefer that the PowerShell window be visible. It doesn't seem to be an intrinsic of PowerShell either; simply starting notepad.exe via Start-Process provides a hidden notepad instance as well.

While I'm aware that I probably shouldn't be relying on console output, it's good enough for my purposes.

Is there a way to invoke a foreground process from a background job?

vmrob
  • 123
  • 1
  • 5

1 Answers1

1

This behavior is by design. PowerShells jobs and Windows scheduled tasks are running in the background (Session 0) and should/do not interact with the user's desktop.

PowerShell jobs are really just Windows scheduled tasks, you can find them at:

\Microsoft\Windows\PowerShell\ScheduledJobs

The only way to run a scheduled tasks to interact with the desktop session is to set: Run only when user is logged on

With schtasks.exe you would use the /IT switch

The ScheduledJobOptions in the PowerShell cmdlets don't seem to let you specify this.

So you could try to manually find the scheduled tasks corresponding to your PowerShell Job and change that property.

Peter Hahndorf
  • 14,058
  • 3
  • 41
  • 58
  • I ended up solving the problem by using Scheduled Tasks instead of jobs. I was unable to find, anywhere, an answer to the question, but launching an interactable PowerShell session via Register-ScheduledTask was easy enough. – vmrob Jun 23 '15 at 21:32