powershellcsvselect-objectline-countmeasure-object

How to only get one column output for Measure-Object Powershell


I'm trying to get the line count of a csv file. I ran this code to get it:

$csvPath = "some.csv"
$lineCount = "linecount.csv"
Import-Csv $csvPath | Select-Object -Skip 1 | Measure-Object | Export-CSV $lineCount -NoTypeInformation

This is the output I get in linecount.csv:

"Count","Average","Sum","Maximum","Minimum","Property"
"100",,,,,

This is my desired output:

"Count"
"100"

How can I achieve this?


Solution

  • To select a subset of the properties from an object / each object in a collection, pipe them to Select-Object and pass the property names of interest to the -Property parameter.

    Therefore, to get only the Count property (using a simplified example):

    # To pass *multiple* property names, separate them with ","
    # Since -Property is the first positional parameter, you may omit its name.
    1..10 | Measure-Object | Select-Object -Property Count
    

    Note:


    As for you what you're counting:


    [1] In an effort to reflect the type of the objects that the properties were taken from, the output objects are assigned an additional type name, via PowerShell's ETS (Extended Type System), formed by prepending Selected. to the full type name of the input objects. In this example: Selected.Microsoft.PowerShell.Commands.GenericMeasureInfo. This ETS type name surfaces when you pass such instances to Get-Member, for instance, and also as the first entry of the instrinsic .pstypenames property value and in the type-identifying comment added to CSV output by Export-Csv / ConvertTo-Csv if -NoTypeInformation is not used in Windows PowerShell / if -IncludeTypeInformation is used in PowerShell (Core) 7+.

    [2] This even works with multiple input objects, courtesy of PowerShell's member-access enumeration feature. However, this requires collecting all input objects in memory, up front. While this generally won't be a problem, it could be with large input collections where processing the property values one by one must be performed; in that case, use the Select-Object or ForEach-Object techniques.