Search code examples
powershellautomation

How to send text/string when key is pressed powershell


I want to make macros using function keys to improve my workflow but the code below doesnt work, i think its quite self explanatory, while the code is running if i press X key, a different text is sent.

$wshell = New-Object -ComObject wscript.shell;  
# choose the key you are after
$key = [System.Windows.Input.Key]::LeftCtrl
$isCtrl = [System.Windows.Input.Keyboard]::IsKeyDown($key)    
while ($true)
{
if ($isCtrl)
{
    $wshell.SendKeys('Thank you for using the service.')
}
}

The code above doesnt work. But if i only use the code below it does send the string as expected.

$wshell = New-Object -ComObject wscript.shell; 
sleep 1
$wshell.SendKeys('Digital service desk')

Solution

  • As stated by Mathias R. Jessen i was not updating the value of $isCtrl inside the loop. I'll now post the code if anyone wants to use it.

    $wshell = New-Object -ComObject wscript.shell;
    
    
    
    Add-Type -AssemblyName WindowsBase
    Add-Type -AssemblyName PresentationCore
    
    
    while ($true)
    {
    if ([System.Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::F2))
    {
    sleep 1
    $wshell.SendKeys('Message after pressing F2')
    } elseif ([System.Windows.Input.Keyboard]::IsKeyDown([System.Windows.Input.Key]::F4)){
    sleep 1
    $wshell.SendKeys('Message after pressing F4')
    }
    }