pepco
pepco

Reputation: 67

powershell strange behaviour for where-object

I have a simple configuration CSV:

Operation;Job_ID
PROD1;0
CA1;0
CON1;0
CON2;0
ADDR1;0

I load the config into the variable and during the processing I update the configuration. To keep it simple I will show you one simple example of what I'm doing; in reality the script is much more complex:

$Config = import-csv -delimiter ";" .\tst.csv
($Config | ? {$_.Job_ID -eq 0}).count #returns 5
$Config[0].Job_ID = 1
$Config[1].Job_ID = 2
$Config[2].Job_ID = 3
($Config | ? {$_.Job_ID -eq 0}).count #returns 2
$Config[4].Job_ID = 5
($Config | ? {$_.Job_ID -eq 0}).count #returns nothing

Could you please explain why the last count displays nothing? In reality it should return 1.

I can rewrite the "count" to a foreach loop, but I'd like to know if there is a better way to work around this issue.

Thank you.

Upvotes: 1

Views: 83

Answers (2)

TheMadTechnician
TheMadTechnician

Reputation: 36297

It does not return 1 because it is no longer an array that is returned, but a PSCustomObject since there is only 1 result. That object does not have a Count method associated with it like an array would. You want it to return a count value? Make it an array by adding an @ prefix.

$Config = import-csv -delimiter ";" .\tst.csv
@($Config | ? {$_.Job_ID -eq 0}).count #returns 5
$Config[0].Job_ID = 1
$Config[1].Job_ID = 2
$Config[2].Job_ID = 3
@($Config | ? {$_.Job_ID -eq 0}).count #returns 2
@($Config | ? {$_.Job_ID -eq 0}).count #returns 1

Upvotes: 1

mjolinor
mjolinor

Reputation: 68273

If a PowerShell expression returns more than one object, the return will be an array of objects. If it only returns one object it will just be that object, not an array of one object. Since it's not returning an array, there's no count property, so you get null. One workaround is to wrap the expression in @() so it's forced into an array:

@($Config | ? {$_.Job_ID -eq 0}).count 

Upvotes: 4

Related Questions