How to use the StreamReader class in Powershell to find and count number of characters contained in a file?

后端 未结 1 512
温柔的废话
温柔的废话 2020-12-21 05:32

I\'m new to powershell and have no experience with .net. I have a script that use
(get-content | select-string -pattern -allmatches).matches | measure-object

1条回答
  •  失恋的感觉
    2020-12-21 06:04

    You can use ToCharArray and where to find the matches. For example, to count the number of "e" in the file you can say:

    $file = get-item ''
    
    $reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $file
    
    [int]$count = 0
    
    while ( $read = $reader.ReadLine() ) {
    
        $matches = ($read.ToCharArray() | where {$_ -eq 'e'}).Count
        $count = $count + $matches
    }
    

    0 讨论(0)
提交回复
热议问题