windowspowershellcmdsendkeysshortcut-file

Running SendKeys commands from a .lnk (shortcut) with powershell doesn't work


I'm playing around with SendKeys and powershell. I tried to close the active window with SendKeys (ALT + F4) after running a shortcut. I got this working with adding the following command to the Target field of a Windows shortcut(.lnk):

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\Users\user\Documents\TEST\test.ps1"

Code in test.ps1:

(New-Object -ComObject Wscript.Shell).SendKeys("%{F4}")

When I run the shortcut the active windows closes. Now I wanted to make this work without .ps1 script. I tried to run the powershell command from the Target field of the shortcut and that didn't work.

The commands I added to the shortcut Target field that didn't work:

$ C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe $wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")
$ C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")"
$ C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe (New-Object -ComObject Wscript.Shell).SendKeys("%{F4}")
$ C:\Windows\System32\cmd.exe /c powershell.exe -noprofile -executionpolicy bypass $wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")
$ C:\Windows\System32\cmd.exe /c powershell.exe -noprofile -executionpolicy bypass "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")"
$ C:\Windows\System32\cmd.exe /c powershell.exe -noprofile -executionpolicy bypass (New-Object -ComObject Wscript.Shell).SendKeys("%{F4}")

What I'm doing wrong in the commands above? I need to use a different syntax when I run powershell commands from Shortcuts?


Solution

  • What I'm doing wrong in the commands above?

    Additionally, for full robustness, it is best to pass the entire PowerShell command inside a single (unescaped) "..." string.

    Therefore:

    powershell.exe -noprofile -executionpolicy bypass "(New-Object -ComObject Wscript.Shell).SendKeys(\"%{F4}\")"
    

    However, given that, in the context of your PowerShell command, a single-quoted string ('...') to represent the key combination %{F4} argument will do (and is arguably preferable, given that you only need "..." quoting in PowerShell for string interpolation), you can simplify to:

    powershell.exe -noprofile -executionpolicy bypass "(New-Object -ComObject Wscript.Shell).SendKeys('%{F4}')"