I am using powershell and using Invoke-SqlCmd
. I am able to pass variables to SQL:
$variables = @( "MyVariable='hello'" )
Invoke-SqlCmd `
-ServerInstance 'localhost' `
-Database 'master' `
-Username 'matthew' `
-Password 'qwerty' `
-Query 'SELECT $(MyVariable) AS foo' `
-Variable $variables
This gives me back hello
as expected. However, if I have a variable with a value containing an equals (=
):
$variables = @("MyVariable='aGVsbG8NCg=='") # base64 encoded 'hello'
It gives me the following error:
The format used to define the new variable for
Invoke-Sqlcmd
cmdlet is invalid. Please use the 'var=value' format for defining a new variable.
I could not find any documentation on either sqlcmd
or Invoke-SqlCmd
on how I should escape values properly.
How do I escape variables sent to sqlcmd
/ Invoke-SqlCmd
?
The Invoke-Sqlcmd cmdlet runs a script containing the languages and commands supported by the SQL Server SQLCMD utility. The commands supported are Transact-SQL statements and the subset of the XQuery syntax that is supported by the database engine.
SQLCMD variables can be a useful way of having changeable parameters for your SQL scripts, allowing you to specify the value from a command line, but also to control things you couldn't manage through a SQL variable.
The official SqlServer module now includes a version of the Invoke-Sqlcmd cmdlet that runs in PSCore 6.2 and above. The version of the SqlServer module which contains this cmdlet is 21.1. 18095-preview and is available in the PowerShell Gallery.
Use CHAR(61)
to replace the equal sign.
$variable = "'Hello=World'"
$variables = @( "MyVariable=$($variable.replace("=","'+CHAR(61)+'"))" )
Invoke-SqlCmd -ServerInstance 'localhost' -Database 'master' -Query 'SELECT $(MyVariable) AS foo' -Variable $variables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With