Search code examples
powershellbatch-fileescapingquotes

Escaping quotes in powershell command issued by batch file


I've been trying to get a PowerShell command to create a shortcut working in a batch file but can't get it to actually put the quotes I need in the shortcut. I've used this command in other batch files just fine, but the quotes are messing it up. I've tried "", """, """", ", ", \", `", and pretty much every variation I can think of and nothing has worked. I need the shortcut to be this:

"C:\Program Files\OpenVPN\bin\openvpn-gui.exe" --connect "mullvad.ovpn"

And here's what I've been trying, of course with the numerous variations:

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\OpenVPN GUI.lnk');$s.TargetPath='"C:\Program Files\OpenVPN\bin\openvpn-gui.exe" --connect "mullvad.ovpn"';$s.Save()"

But it either just creates a shortcut to this:

"C:\Program Files\OpenVPN\bin\openvpn-gui.exe --connect mullvad_us_chi.ovpn"

or, more often, it errors because the syntax is wrong with my various attempts. So how do I get PowerShell to do what I want here?


Solution

  • Your main issue is that you aren't correctly creating a shortcut.

    In order to do so, you should first of all use an additional property. Your TargetPath should be the executable, and the rest, its Arguments:

    Then your command should look a little more like this:

    "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -Command "$s = (New-Object -COM WScript.Shell).CreateShortcut(\"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\OpenVPN GUI.lnk\");$s.TargetPath=\"C:\Program Files\OpenVPN\bin\openvpn-gui.exe\";$s.Arguments=\"--connect `\"mullvad.ovpn`\"\";$s.Save()"
    

    I rarely use single quotes, but if you prefer them then perhaps this would also work for you:

    "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -Command "$s = (New-Object -COM WScript.Shell).CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\OpenVPN GUI.lnk');$s.TargetPath='C:\Program Files\OpenVPN\bin\openvpn-gui.exe';$s.Arguments='--connect \"mullvad.ovpn\"';$s.Save()"