THE SQL Server Blog Spot on the Web

Welcome to - The SQL Server blog spot on the web Sign in | |
in Search

Jamie Thomson

This is the blog of Jamie Thomson, a data mangler in London working for Dunnhumby

Issuing linux commands with embedded quotes from PowerShell.

Here’s a little thing I figured out today and I’m sticking it on my blog because I know I’ll need this again at some point.

I’ve been writing some PowerShell code to connect to linux and issue bash commands (don’t ask why ). We use PLink.exe, a free utility that is bundled inside putty, to issue the commands hence our code is something like this:


Here’s the result:


Simple enough. The difficulty comes though if the string that you want to echo contains embedded quotes, like this:


It still runs without error but the same message gets output. The embedded quotes have been lost. I discovered (thanks to “Duncan” on Stack Overflow) that you need to (a) use a backslash to escape the quotes so that bash understands them and (b) do some fancy replacing using regex which I wrapped up in a function Set-EmbeddedQuotesInLinuxCommand. Hence my code now looks like this:


And then we get the result we’re after:


Quite frankly I don’t fully understand the intricacies of why this works but work it does and that’s all I care about. Here’s the code so you can copy and paste:

function Set-EmbeddedQuotesInLinuxCommand ($Command) {
    return (  $Command -replace '(\\*)"','$1$1\"'  )

$hostname = "<redacted>"
$user = "<redacted>"
$password = "<redacted>"

$plinkPath = gci . -Recurse | `
                Where-Object {$_.Name -eq "plink.exe"} | `
                Select-Object -First 1 | `
                ForEach-Object {$_.FullName}  #assumes that plink.exe exisst somewhere under your current folder
$greeting  = '\"Hello world!\"'   ##########Embedded quotes############
$greeting = (Set-EmbeddedQuotesInLinuxCommand $greeting )
$arguments = @()
$arguments += "$User@$hostname","-pw",$password,"echo",$greeting

& $plinkPath $arguments

Obviously this is a bit of a contrived example (echoing strings isn’t particularly useful), in reality our use case was a lot more complicated as we were passing connection strings and SQL statements to be issued – the principle is the same though. Hope this helps.


Published Thursday, January 21, 2016 4:57 PM by jamiet
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS


No Comments

Leave a Comment


This Blog


Privacy Statement