Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing path to SqlCmd within powershell script

I'm trying to write a powershell script which will execute sqlcmd.exe to run a sql script. The script contains a SQLCMD variable which I want to pass in on the command line via sqlcmd's -v switch. The problem is that powershell is doing something weird when I pass a path as the value of one of my variables which in turn causes the SQL script to fail.

For example I'm calling:

$path = 'C:\path'
sqlcmd -SMySQLServerInstance  -i 'MySqlScript.sql'  -v MyVariablePath=$path

when run I receive a error which says:

Sqlcmd: ':\path': Invalid argument.

No amount of double or single quotes that I have tried around $path or MyVariablePath=$path solves the issue.

Can somebody provide a simple canonical example of how this needs to be done?

like image 738
Dav Evans Avatar asked Sep 17 '10 10:09

Dav Evans


People also ask

What does invoke-Sqlcmd do?

Description. 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.


2 Answers

finally worked it out. for the next sucker to try this here is the solution

powershell script looks like

$myPath = "`"C:\Path`"" 
sqlcmd.exe -SmySQLInstance -i./test.sql -v myvar=$myPath

my test.sql file can then use the variable like this

PRINT "$(myvar)"

the key here is understanding how powershell does escape characters. More info on that here

like image 151
Dav Evans Avatar answered Oct 17 '22 03:10

Dav Evans


Had the same issue, found the solution accidentally, still don't understand why it works :) (i'm not a powershell pro though):

sqlcmd -d ... -s ... -v Var1Name=("""$PowershellVar1""") Var2Name=("""$PowershellVar2""")

Variables $PowershellVar1 and $PowershellVar2 have string type in my PS script and can contain quotes, spaces etc

like image 27
Andrei Shakh Avatar answered Oct 17 '22 01:10

Andrei Shakh