Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape variable in sqlcmd / Invoke-SqlCmd

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?

like image 616
Matthew Avatar asked Feb 02 '16 15:02

Matthew


People also ask

What does invoke-Sqlcmd do?

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.

What is Sqlcmd variable?

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.

Which module is invoke-Sqlcmd in?

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.


1 Answers

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
like image 52
Jeroen Jongman Avatar answered Oct 15 '22 19:10

Jeroen Jongman