2022-07-26

[console]::KeyAvailable is not identified while running from startup

The script task is to respond to keyboard commands 'F3' and 'F4'

When running the script from terminal or CMD it is fully functional However, when calling the script from start-up cmd, the script is running but not receiving the commands from keyboard

Any idea why behavior is different when running from startup ?

This is the command line:

powershell  -WindowStyle hidden -ExecutionPolicy Bypass C:\PowerShell\KeyBoardTest\Keyboard-Command-Response.ps1 >>  C:\PowerShell\KeyBoardTest\Keyboard-Command-Response_log.log

This is the PowerShell script:

$shell = New-Object -ComObject "Shell.Application"
$Pause_script = 0
$exit_command = 'FALSE'

Sleep -Seconds 3
$Res= $shell.minimizeAll()

While ($exit_command -eq 'FALSE')
{
    Sleep -Seconds 1
    Write-Output "Mylog: Waiting to Keyboard"
    if ([Console]::KeyAvailable)
    {
        
        $KeyPressed = [System.Console]::ReadKey() 
        Write-Output "Mylog: Identified Press of key"
        switch ($KeyPressed.key)
        {
        F3 { 
            if ($Pause_script -eq 0){
                $Pause_script = 1
                Write-Output "Mylog: F3 Detected, Pausing Run"
                }
            else{
                $Pause_script = 0 
                Write-Output "Mylog: F3 Detected, Resuming Run"   
                }
            }
        F4 {
            $exit_time = Get-Date
            [DateTime]$Date = $exit_time
            $mytime = $date.ToShortDateString() + " " + $date.ToShortTimeString()
            Write-Output "Mylog: F4 Detected, Exiting the loop at: $mytime"
            $Exit_Command = 'TRUE'
            break
            }
        }
    }
}

The log when running from terminal (and not from startup) (when pressing F3 5 times and F4 one time)

Mylog: Waiting to Keyboard
Mylog: Waiting to Keyboard
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Pausing Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Resuming Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Pausing Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Resuming Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Pausing Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F4 Detected, Exiting the loop at: 7/23/2022 2:35 PM


No comments:

Post a Comment