0

I am facing the error "Input string was not in a correct format." while using the variable in for loop.

$totalrows=$filepath |% {$n = $_; $c = 0; Get-Content -Path $_ -ReadCount 1000 |% { $c += $_.Count }; "$n; $c"}
echo $totalrows

Output is 8 and it is correct.

Used this variable in for loop:

For ($i = 0; $i -lt $totalrows; $i++) {
    Write-host $i 
} 

but i get the error :

8" to type "System.Int32". Error: "Input string was not in a correct format."

So, I looked into SO for same questions so i found to typecast into integer:

$totalrows=$filepath |% {$n = $_; $c = 0; Get-Content -Path $_ -ReadCount 1000 |% { $c += $_.Count }; "$n; $c"}
$totalrowscast=[int]$totalrows
echo $totalrowscast

For ($i = 0; $i -lt $totalrowscast; $i++) {
    Write-host $i 
} 

But still I am facing the same error.

5
  • Put a write-host $totalrows.gettype() to see what type you are getting. Commented Feb 2, 2022 at 9:42
  • System.String its printing Commented Feb 2, 2022 at 9:43
  • What do you expect? The last item on pipeline is a string: "$n; $c" that will give you a string that contains two things separated with a semicolon. Commented Feb 2, 2022 at 9:51
  • i expect the variable $totalrows to be integer. Commented Feb 2, 2022 at 9:52
  • Then just output $c, not "$n; $c" Commented Feb 2, 2022 at 10:09

1 Answer 1

1

You're outputting a single string containing both the path AND the row count, eg. "path; 8", which can't be converted to a numerical type, hence the error.

You don't need to manually count each chunk read by Get-Content - the cmdlet already adds a line number to each string it outputs, so you can simply discard everything but the last line and its line number will be the line count (excluding any trailing newline):

$totalrows = Get-Content $filepath |Select -Last 1 -ExpandProperty ReadCount

The ReadCount property is already an [int], so everything will start working expected, including $i -lt $totalrows

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.