Escaping strings containing single quotes in PowerShell ready for SQL query

Question:

I am trying to run the following query, which takes someone’s name and attempts to insert it into an SQL Server database table.

The problem I am facing is that the single quote is causing an issue in my query. The query is being executed as

which causes an SQL syntax error.

My question is how do I escape my $name variable so that it renders on the SQL side.

One solution is to do a find and replace on my $name variable, find: ‘ replace: ”

Is there a more elegant solution out there, or a function that I can’t seem to find?

Thank you.

Answer:

You can try to update your code to to use a parametrised value that will cope with quotes in a string:

I’m not experienced with powershell but referenced this post for a parametrised query:

Source:

Escaping strings containing single quotes in PowerShell ready for SQL query by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply