'Powershell script works when executed directly in Powershell, but not when executed from Task Scheduler

I have a PS script with an embedded condition. If true, it displays a prompt. If the user enters "R", the PC is supposed to reboot. Everything works well when the script is executed manually, but when executed via Task Scheduler, the task runs, but no prompt is displayed.

In Task Scheduler, History shows the task as having been completed with Operational Code (2). Task Action =

Blockquote -ExecutionPolicy Bypass "{script path}\TimeToReboot.ps1" Blockquote

This is the same action I'm using for other scheduled tasks, which work without issue. Not sure what I'm doing wrong. Thanks in advance - any advice will be appreciated. Script shown below.

enter code here
# Definitions
    $RebootTriggerDays = 5
    $CompName = $env:computername

    $RebootTime = (gcim Win32_OperatingSystem).LastBootUpTime
    $TimeSinceReboot = (get-date) - $RebootTime
    $DaysSinceReboot = $TimeSinceReboot.TotalDays # $TimeSinceReboot| Select-Object -ExpandProperty TotalDays
     
if ($DaysSinceReboot -gt $RebootTriggerDays) {
    Write-host $CompName 'last Restarted:' $RebootTime `n 'Days since ReBooting:' ([math]::Round($DaysSinceReboot, 2))

    $Action = Read-Host -Prompt "Enter 'R' to ReBoot now (anything else to skip)"
    if ($Action.ToUpper -eq 'R') { Restart-Computer -ComputerName $CompName -Confirm }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source