4

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
  • You could do $markdownlinkstoProcess.GetLength(0) or @($markdownlinkstoProcess.GetEnumerator()).Count to get the number of rows in the csv. $markdownlinkstoProcess.GetUpperBound(0) + 1 should also do the trick. Commented Nov 10, 2018 at 14:28

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.