Home > other >  Input string was not in a correct format in powershell
Input string was not in a correct format in powershell

Time:02-03

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.

CodePudding user response:

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

  •  Tags:  
  • Related