How can I use the StreamReader class in Powershell to find and count the number of characters contained in a file?
I am new to powershell and have no experience with .net. I have a script that use
(get-content | select-string -pattern -allmatches).matches | measure-object
find and count the number of characters in a file. My script will work fine if the file contains less than 10k lines. Otherwise for a large file the RAM will shoot up to 100% and then Powershell will display (not responding)
I did some research and I found out that system.io.streamreader will work, I read a couple of questions on Stackoverflow and found and matched a character or word in a file you just have to do:
$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 only returns the number of lines containing a character, but not the number of characters in the file. So how should I use (select-string -inputobject -pattern -allmatches).matches | measure-object
with streamreader?
source to share
You can use ToCharArray
and where
to find matches. For example, to count the number of "e" s in a file, you might 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
}
source to share