2015-08-28 107 views
0

我有以下PS脚本来计算。有没有一种方法可以在不导入整个csv的情况下统计(减去标题)?有时候csv文件非常大,有时它没有记录。在csv文件计数记录 - Powershell

Get-ChildItem 'C:\Temp\*.csv' | ForEach { 
    $check = Import-Csv $_ 
    If ($check) { Write-Host "$($_.FullName) contains data" } 
    Else { Write-Host "$($_.FullName) does not contain data" } 
} 

回答

1

计数行,而不用担心头使用这样的:

$c = (Import-Csv $_.FullName).count 

然而,这需要读取整个文件到内存中。计数文件更快的方法是使用Get-内容与readcount标志,像这样:

$c = 0 
Get-Content $_.FullName -ReadCount 1000 | % {$c += $_.Length} 
$c -= 1 

要从计数删除标题行,你只是减去1.如果没有行唐”你的文件吨有一个头,你可以避开他们零下1像这样计算:有以下特点

$c = 0 
Get-Content $_.FullName -ReadCount 1000 | % {$c += $_.Length} 
$c -= @{$true = 0; $false = - 1}[$c -eq 0] 
0

这里是将检查的CSV文件中的空函数(返回True如果是空的,False否则):

  • 可以跳过标题
  • 工程在PS 2.0(PS 2.0有不-ReadCount开关Get-Content小命令)
  • 不在存储器加载整个文件
  • 意识到CSV文件结构的(不会计数空/无效的行)。

它接受下列参数:

  • 文件名路径CSV文件。
  • MaxLine从文件中读取的最大行数。
  • NOHEADER如果没有指定此开关,功能将跳过该文件的第一行

用例:

Test-IsCsvEmpty -FileName 'c:\foo.csv' -MaxLines 2 -NoHeader 

function Test-IsCsvEmpty 
{ 
    Param 
    (
     [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] 
     [string]$FileName, 

     [Parameter(ValueFromPipelineByPropertyName = $true)] 
     [ValidateRange(1, [int]::MaxValue)] 
     [int]$MaxLines = 2, 

     [Parameter(ValueFromPipelineByPropertyName = $true)] 
     [switch]$NoHeader 
    ) 

    Begin 
    { 
     # Setup regex for CSV parsing 
     $DQuotes = '"' 
     $Separator = ',' 
     # http://stackoverflow.com/questions/15927291/how-to-split-a-string-by-comma-ignoring-comma-in-double-quotes 
     $SplitRegex = "$Separator(?=(?:[^$DQuotes]|$DQuotes[^$DQuotes]*$DQuotes)*$)" 
    } 

    Process 
    { 
     # Open file in StreamReader 
     $InFile = New-Object -TypeName System.IO.StreamReader -ArgumentList $FileName -ErrorAction Stop 

     # Set inital values for Raw\Data lines count 
     $CsvRawLinesCount = 0 
     $CsvDataLinesCount = 0 

     # Loop over lines in file 
     while(($line = $InFile.ReadLine()) -ne $null) 
     { 
      # Increase Raw line counter 
      $CsvRawLinesCount++ 

      # Skip header, if requested 
      if(!$NoHeader -and ($CsvRawLinesCount -eq 1)) 
      { 
       continue 
      } 

      # Stop processing if MaxLines limit is reached 
      if($CsvRawLinesCount -gt $MaxLines) 
      { 
       break 
      } 

      # Try to parse line as CSV 
      if($line -match $SplitRegex) 
      { 
       # If success, increase CSV Data line counter 
       $CsvDataLinesCount++ 
      } 
     } 
    } 

    End 
    { 
     # Close file, dispose StreamReader 
     $InFile.Close() 
     $InFile.Dispose() 

     # Write result to the pipeline 
     if($CsvDataLinesCount -gt 0) 
     { 
      $false 
     } 
     else 
     { 
      $true 
     } 
    } 
}