Home Dashboard Directory Help

Splat operator required to get count of single-item CSV by Brandon Moxley



Sign in
to vote
Type: Bug
ID: 807403
Opened: 11/1/2013 4:36:16 AM
Access Restriction: Public
User(s) can reproduce this bug


When using Import-Csv, if the CSV only has 1 line (in addition to the header row), you cannot simply call "$file.Count" to get the number of lines. To get the count of a single-line CSV, you must use the splat operator (@) before the variable to tell PowerShell it is an Array. For some reason, it sees the single-line file as a PSCustomObject, whereas any other length of CSV file comes back as an Array, as expected.
Sign in to post a comment.
Posted by Brandon Moxley on 11/20/2013 at 9:05 AM
Thanks PerSalAl. That makes sense.
Posted by PetSerAl on 11/20/2013 at 8:45 AM
Import-Csv return only PSCustomObject objects, so datatype actually does not change whether there are one or 100 items. Import-Csv does not return arrays. Array is the result of pipeline invocation: if pipeline return more than one object, than in have to be packed into array, to be assigned to variable. It is how PowerShell works. If pipeline return only one object, then PowerShell does not wrap it into array. So you can write something like this: (Get-Item FileName.ext).CreationTime . You does not need to unwrap result of Get-Item cmdlet, because it return just one item. If you need array even in case of one or zero item from pipeline, then you need to use @() operator. Anyways, changing this would affect compatibility to much, so it is vary unlikely, what this behavior would be changed.
Posted by Brandon Moxley on 11/4/2013 at 8:43 AM
Thanks for the response PetSerAl. Is there any reason it sees it as a PSCustomObject when there is only one item? I would think that if you use Import-Csv that the datatype wouldn't change whether there are one or 100 items.
Posted by PetSerAl on 11/2/2013 at 9:01 PM
So Count and Length auto properties (come with v3) does not work on PSCustomObject (([PSCustomObject]@{Name='Value'}).Count). Returning object itself, when pipeline return only one object, it is expected behavior since PowerShell v1 and have nothing to do with Import-Csv.
Sign in to post a workaround.
Posted by Brandon Moxley on 11/1/2013 at 4:37 AM
The workaround for this is to use the splat operator to ensure PowerShell knows it is an array.

i.e. instead of using "$file.Count", use "@($file).Count"