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?
2 Answers
Should be simple. Let's assume the CSV field is called Result:
$result = (Import-Csv .\sqlout.csv).Result
5 Comments
mhopkins321
is there a way to do it without creating the csv in sqlcmd?
Joey
You could use the SqlServerCmdletSnapin. Look for it in
Get-PSSnapin -Registered and add it with Add-PSSnapin.Keith Hill
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 ....mhopkins321
the result would be something along the lines of accounts 12
Keith Hill
In that case
$sqlout = sqlcmd.exe ...; $result = $sqlout.Split(' ')[1]. This splits on a space and grabs the second element in the resulting array.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
n8.
This worked for me without the "Add-PSSnapIn SqlServerCmdletSnapin100" part