PowerShell property Count cannot be found on this object

5k Views Asked by At

I am trying to count some lines output by a command. Basically all the lines which end in " Y " in this example.

Fist Capture the command results:

PS> $ItsAgents = tacmd listSystems -n Primary:SomeHost:NT
PS> $ItsAgents
Managed System Name      Product Code Version     Status
Primary:SomeHost:NT NT           06.30.07.00 Y
SomeHost:Q7         Q7           06.30.01.00 N

Now count the online ones:

PS> $AgentCount = ($ItsAgents | Select-String ' Y ').Count
PS> $AgentCount 
1

Now that all works as I expect. So I put it in my script like this:

$ItsAgents = tacmd listSystems -n $agent
Write-Host $ItsAgents
$BeforeCount = ($ItsAgents | Select-String ' Y ').Count

And when the script runs (under Set-StrictMode) I get:

The property 'Count' cannot be found on this object. Verify that the
property exists.
At Y:\Scripts\newMoveAgents.ps1:303 char:7
+             $BeforeCount = ($ItsAgents | Select-String ' Y ').Count
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
+ FullyQualifiedErrorId : PropertyNotFoundStrict

The Write-Host does output sane results so $agent is set correctly and the tacmd command is running OK So why does it fail in the script, but work on command line?

1

There are 1 best solutions below

1
On BEST ANSWER

Use the @() operator to force the output to always be an array:

$BeforeCount = @($ItsAgents | Select-String ' Y ').Count

The array sub-expression operator creates an array, even if it contains zero or one object. (Microsoft Docs)

Note: Afaik it should work the same way both as a script and inside the console. Maybe your commands produce different output, where the console version returns 2+ results but for some reason the script version only 1 or 0 results, which would be the reason why there is no Count property.