6

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
to find and count how many characters in a file. My script will work fine if the file only contain less than a 10k rows. Otherwise for big file, the RAM will shoot up to 100% and then the Powershell will display (Not Responding)

I did some research and I found out system.io.streamreader will work, I read a couple of questions in Stackoverflow and to find and match the character or word in a file you just need do this:

$file = get-item '<file path>'

$reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $file

[int]$line = 0

while ( $read = $reader.ReadLine() ) {

    if ( $read -match '<charcter>' ) {

        $line++

    }

}

but this is only returning the number of lines that contain the character, but not the number of characters in a file. So how do I use (select-string -inputobject -pattern -allmatches).matches | measure-object with the streamreader?

0

1 Answer 1

8

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 '<file path>'

$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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.