Sendkeys - long string with `"` and `'` and `(` characters

I would like to make powershell send keyboard output using SendKeys (if there’s anything else I’m not familiar with - let me know), but it’s a sentence that involves characters like ' and (:

Add-Type -AssemblyName System.Windows.Forms
$bar='document.getElementsByClassName('foo')[0].click()'
[System.Windows.Forms.SendKeys]::SendWait($bar)

I just want to send the following sentence:

document.getElementsByClassName('foo')[0].click()

I tried a few things - changing ' to ", but even if I solve that I don’t know how to make it so powershell will send the ( characters in the same sentence.

If I try:

Add-Type -AssemblyName System.Windows.Forms
$bar="document.getElementsByClassName('foo')[0].click()"
[System.Windows.Forms.SendKeys]::SendWait($bar)

I get:

document.getElementsByClassName'foo'[0].click

Which doesn’t include the ( and ).

SendKeys Class (System.Windows.Forms) | Microsoft Learn

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses () have special meanings to SendKeys. To specify one of these characters, enclose it within braces ({}). For example, to specify the plus sign, use “{+}”. To specify brace characters, use “{{}” and “{}}”. Brackets () have no special meaning to SendKeys, but you must enclose them in braces. In other applications, brackets do have a special meaning that might be significant when dynamic data exchange (DDE) occurs.

This is ugly but it seems to work:

Add-Type -AssemblyName System.Windows.Forms
$bar = "document.getElementsByClassName{(}'foo'{)}{[}0{]}.click{(}{)}"
[System.Windows.Forms.SendKeys]::SendWait($bar)
#Output = document.getElementsByClassName('foo')[0].click()

Note that I did add curly braces around the brackets, mostly cuz the docs stated you should do so.

1 Like

Perfect! Thank you very much!

You’re most welcome.