2

I am running an sql query that will save the result into a csv. The only thing in the csv is the return of a COUNT() function. Is there a way that I can save this number directly into a variable in powershell?

1
  • Vutukuri, since the result is in a CSV it doesn't really matter. Commented Apr 26, 2012 at 17:17

2 Answers 2

2

Should be simple. Let's assume the CSV field is called Result:

$result = (Import-Csv .\sqlout.csv).Result
Sign up to request clarification or add additional context in comments.

5 Comments

is there a way to do it without creating the csv in sqlcmd?
You could use the SqlServerCmdletSnapin. Look for it in Get-PSSnapin -Registered and add it with Add-PSSnapin.
Not as familiar with sqlcmd.exe but if you can get it to output a single number like 12 then just do this $result = sqlcmd.exe .... To force the result to a number (instead of a string): [int]$result = sqlcmd.exe ....
the result would be something along the lines of accounts 12
In that case $sqlout = sqlcmd.exe ...; $result = $sqlout.Split(' ')[1]. This splits on a space and grabs the second element in the resulting array.
1

If you want to get rid of the CSV you could use the SqlServerCmdletSnapin:

Add-PSSnapIn SqlServerCmdletSnapin100
(Invoke-Sqlcmd -server .\sqlexpress -database foo -query 'SELECT COUNT(...) FROM ...')[0]

1 Comment

This worked for me without the "Add-PSSnapIn SqlServerCmdletSnapin100" part

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.