【问题标题】:Powershell 2.0 to count columns in a filePowershell 2.0 对文件中的列进行计数
【发布时间】:2020-03-31 08:44:57
【问题描述】:

我需要检查文本文件并确定在列号方面是否存在任何不匹配。如果有,应该有一个错误信息。

我找到了下面的解决方案,因为分隔符是“,”,所以我对其进行了调整: Powershell to count columns in a file.

代码如下:

$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}
        }

如果使用 powershell 5.1,这可以正常工作,但在 2.0 版中运行时遇到错误消息。错误信息:

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

由于我需要使用 2.0 版,因此可以在可以在 2.0 版上运行的 powershell 脚本中进行转换吗?还是有一个批处理命令脚本也可以做到这一点?任何帮助/建议将不胜感激。

【问题讨论】:

  • $_.psobject.Properties.value[5] --> @($_.psobject.properties)[5].value
  • 感谢 AdminOfThings。这是有效的。非常感谢朋友! :)

标签: powershell csv powershell-2.0


【解决方案1】:

试试这个:

$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)"
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多