Unable to get CSV Row count in Powershell

Viewed 965

I have a csv file that's structured like this:

Text,Url
Learning Haskell,https://wiki.haskell.org/Learning_Haskell

I'm attempting to get the row count before I loop over the csv file, because I don't want to start a loop on empty results.

From researching (1,2), it would seem that Import-csv has a .Count property, but for some reason I'm unable to access that property. I'm using Powershell v5.

Code:

[string]$markdownlink = "markdownlinks.csv"
[string]$processedLinks = "completedlinks.txt"

$markdownlinkstoProcess = Import-Csv $markdownlink -Delimiter "," 

# Returns 0
[int]$count=$markdownlinkstoProcess.Count
Write-output $count
1 Answers

when you have ONE data row in a CSV file, the import produces a single object. that has a known bug in that it will report zero as the .Count of the $Var. this appears to happen with anything that returns a single PSCustomObject - but i aint sure of that.

the solution is to force it to be an array. you can cast it as [array] or simply wrap it in @(). using your code for an example ...

$markdownlinkstoProcess = Import-Csv $markdownlink -Delimiter ","
$markdownlinkstoProcess.GetType()
# result = PSCustomObject
$markdownlinkstoProcess.Count
# result = 0

$markdownlinkstoProcess = @(Import-Csv $markdownlink -Delimiter ",")
$markdownlinkstoProcess.GetType()
# result = Object[]
$markdownlinkstoProcess.Count
# result = 1
Related