1

I need to check the text file and determine if there's any mismatch in terms of column number. If there is, there should be an error message.

I have found the solution below which I have tweaked since the delimiter is ",": Powershell to count columns in a file.

Here's the code:

$colCnt = "12_06_2019.txt"
[int]$LastSplitCount = $Null
Get-Content $colCnt | 
    %{
        if($LastSplitCount -and !($_.split(",").Count -eq $LastSplitCount)) 
        {
            "Process stopped at line number $(
            $_.psobject.Properties.value[5]) for column count mis-match."
            break
        }
        elseif(!$LastSplitCount)
        {
            $LastSplitCount = $_.split(",").Count}
        }

This is working fine if using powershell 5.1 but is encountering error message when running in version 2.0. Error Message:

"Cannot index into a null array. At line:1 char:30 + $_.psobject.Properties.value[<<<< 5].`

Can this be converted in powershell script which can be run on version 2.0 as I need to use version 2.0? or is there a batch command script that can also do this? Any help/suggestion will be appreciated.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Rensie
  • 11
  • 5

1 Answers1

0

Try this one:

$file        = "12_06_2019.txt"
$delimiter   = ','
$oldCols     = -1
$lineCounter = 0

foreach( $line in [System.IO.File]::ReadLines($file) )
{
    $lineCounter++
    $cols = @($line -split $delimiter).Count

    if( $oldCols -eq -1 ) {
        $oldCols = $cols
    }
    elseif( $oldCols -ne $cols ) {
        "Column count mis-match at line $($lineCounter)"
    }
}
f6a4
  • 1,684
  • 1
  • 10
  • 13