Escaping strings containing single quotes in PowerShell ready for SQL query

后端 未结 2 1570
情话喂你
情话喂你 2020-12-11 06:30

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         


        
相关标签:
2条回答
  • 2020-12-11 06:41

    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.

    0 讨论(0)
  • 2020-12-11 06:46

    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:

    0 讨论(0)
提交回复
热议问题