﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / Programming / Powershell  / Invoke-Sqlcmd Count / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Wed, 19 Jun 2013 12:55:20 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Invoke-Sqlcmd Count</title><link>http://www.sqlservercentral.com/Forums/Topic1406945-1351-1.aspx</link><description>I agree, it's a pain. It's something they fixed in PowerShell 3.0.I just drop right into my loop if I get a result and it handles it, but I do have to check for $null first:[code="plain"]Import-Module “sqlps” -DisableNameChecking# 1 row#$results = Invoke-Sqlcmd -Query "select top 1 * from sys.tables where 1=1" -ServerInstance ".\SQL2012" -Database "master";# 2 rows#$results = Invoke-Sqlcmd -Query "select top 2 * from sys.tables where 1=1" -ServerInstance ".\SQL2012" -Database "master";# 0 rows$results = Invoke-Sqlcmd -Query "select * from sys.tables where 1=0" -ServerInstance ".\SQL2012" -Database "master";if($results -ne $null){    $results.GetType()    $results.Length    foreach($row in $results)    {        $row[0]    }}[/code]</description><pubDate>Wed, 16 Jan 2013 01:07:32 GMT</pubDate><dc:creator>opc.three</dc:creator></item><item><title>Invoke-Sqlcmd Count</title><link>http://www.sqlservercentral.com/Forums/Topic1406945-1351-1.aspx</link><description>Hello,I searched for this on here and google and didn't see an exact answer to my question, so sorry if it's been asked and answered before.  If I run a query using Invoke-Sqlcmd and put it in a variable: $results = Invoke-Sqlcmd -Query $query -ServerInstance $QueryServer -Database $QueryDB;and I get multiple rows back, I see that $results has a type of System.Array.  I can get a count of the number of returned results by using $results.Length.However if I get only 1 row back, the Type is Syste.Data.DataRow and $results.Length is NULLI've gotten around this by creating a new variable called ResultsLen and doing the following:$resultsLen = $results.&amp;lt;field in query&amp;gt;.Length$resultsLen += $results.Lengthbut this doens't really work, as the $results.&amp;lt;field in query&amp;gt;.Length is a count of the number of characters in the returned field.  this works for what I need...which is just to run a IF statement to only run some code if there are 1+ records returned in the query...but I'm wondering if there is a better way of doing it?Thanks.</description><pubDate>Mon, 14 Jan 2013 14:17:34 GMT</pubDate><dc:creator>Eric Zierdt</dc:creator></item></channel></rss>