I am trying to run the following query, which takes someone\'s name and attempts to insert it into an SQL Server database table.
$name = \"Ronnie O\'Sullivan
Tanner's helpful answer is definitely the most robust and secure solution, because using a [parameterized / prepared statement (query) eliminates any possibility of a SQL injection attack.
However, in this constrained case, where you want to insert a value into a single-quoted SQL string ('...'
), you can get away with simply doubling any embedded '
characters in the value:
$query = "INSERT INTO People(name) VALUES('$($name -replace "'", "''")')"
The above uses PowerShell's string interpolation via $(...)
, the subexpression operator, to embed an expression that uses the -replace operator to double all embedded '
instances in the value of $name
.
Note: You could also use $name.Replace("'", "''")
above, which performs better in this simple case, but PowerShell's -replace
operator is generally preferable, not only for being PowerShell-native, but for offering superior abilities, because it is regex-based and supports array as its LHS - see this comment on GitHub.
You can try to update your code to to use a parametrised value that will cope with quotes in a string:
$query = "INSERT INTO People(name) VALUES(@name)"
$command = $connection.CreateCommand()
$command.CommandText = $query
$command.Parameters.Add("@name", $name) -- | Out-Null (may be required on the end)
$command.ExecuteNonQuery()
I'm not experienced with powershell but referenced this post for a parametrised query: