1

I'm new to Powershell and getting stuck with some of the syntax. I have a powershell script that calls a SQL script with a variable I want to access inside the script.

param (
[string] $inst = "all"
)

invoke-sqlcmd -inputfile "D:\PowershellScripts\testSQL\testScript.sql" -variable $powerShellVar=$inst -serverinstance '.\sql2008';

in my SQL query I want to be able to access the $powerShellVar variable like this

print $powerShellVar

However, when I do that, I get this error

Invoke-Sqlcmd : Invalid pseudocolumn "$powerShellVar"

What am I doing wrong?

2
  • Seems like variable quotation problem in the sql file. Add the sql script to the post too. Commented Feb 16, 2015 at 9:55
  • @von - I have. The only line it's got is the print statement Commented Feb 16, 2015 at 9:58

1 Answer 1

3

The parameter syntax is invalid. No wonder, as this is poorly documented. The -variable parameter assumes an array that contains name/value pairs like so,

$sqlParameters = @("variable1 = 'value1'", "variable2 = 'value2'")

For just a single parameter,

$sqlParameters = @("variable1 = 'value1'")

By this syntax, assuming printarg.sql contains select $(powerShellVar), this ought work:

$sqlParameters = @("powerShellVar = 'foobar'")
invoke-sqlcmd -ServerInstance computer\instance -inputfile "c:\temp\printarg.sql" -variable $sqlParameters 
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, I've pasted exactly as you have stated into a powershell and sql script and I still get a "Invoke-Sqlcmd : Object reference not set to an instance of an object." error. I think it's to do with select $(powerShellVar). Is there a command to check all the existing variables in the context of an sql query cause it looks like that the variable still doesn't exist.
actually I changed it to this $sqlParameters = "powerShellVar='foobar'" and it worked. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.