PowerShell get number of lines of big (large) file

前端 未结 8 1143
小鲜肉
小鲜肉 2020-12-23 16:35

One of the ways to get number of lines from a file is this method in PowerShell:

PS C:\\Users\\Pranav\\Desktop\\PS_Test_Scripts> $a=Get-Content .\\sub.ps1         


        
8条回答
  •  生来不讨喜
    2020-12-23 17:02

    The first thing to try is to stream Get-Content and build up the line count one at a time, rather that storing all lines in an array at once. I think that this will give proper streaming behavior - i.e. the entire file will not be in memory at once, just the current line.

    $lines = 0
    Get-Content .\File.txt |%{ $lines++ }
    

    And as the other answer suggests, adding -ReadCount could speed this up.

    If that doesn't work for you (too slow or too much memory) you could go directly to a StreamReader:

    $count = 0
    $reader = New-Object IO.StreamReader 'c:\logs\MyLog.txt'
    while($reader.ReadLine() -ne $null){ $count++ }
    $reader.Close()  # Don't forget to do this. Ideally put this in a try/finally block to make sure it happens.
    

提交回复
热议问题