How to Count Lines in a File Using PowerShell
Counting the number of lines in a file is a common need when working with logs, data, or text, and PowerShell provides a clean way to get the count. Windows 11’s PowerShell measures file contents with a straightforward YYGACOR Login command.
The Command
(Get-Content file.txt).Count
What It Does
`Get-Content file.txt` reads the file as a collection of lines, and wrapping it in parentheses with `.Count` returns how many lines there are. This gives you the line count directly as a number, which is useful for checking the size of a log, verifying a data file, or confirming how much content a file holds.
When You’d Use This
This is useful when working with logs, data files, or any text where the line count matters, such as verifying how many records a file holds, checking a log’s size, or confirming an export produced the expected number of lines. A quick count is more reliable than scrolling, and counting matching lines helps quantify occurrences like errors in a log.
Useful Variations
To count lines matching a pattern, pipe to `Select-String` and count those, such as `(Get-Content log.txt | Select-String “error”).Count` for lines containing “error”. To count words or characters instead, `Get-Content file.txt | Measure-Object -Word -Character` provides those totals. The `Measure-Object -Line` approach also counts lines.
If It Doesn’t Work
If counting a very large file is slow or uses too much memory, reading it entirely into memory is the cause, so streaming approaches or `Measure-Object` are more efficient for huge files. If the count seems off by one, consider whether the file ends with or without a final newline. To count words or characters instead, `Measure-Object -Word -Character` provides those totals.
Good to Know
Reading a very large file entirely into memory to count lines can be slow or memory-intensive, so for huge files, streaming approaches or `Measure-Object` are more efficient. The count reflects lines as the file separates them, so a file ending without a final newline still counts its last line normally.
Putting It Together
Once you have run it once or twice, this becomes second nature. As part of working with output and building simple automation, this command is a building block you will reuse constantly. As you combine it with the other scripting basics here, small one-off commands grow into reusable scripts that save real time on repetitive work. Like anything in the terminal, the real value comes from trying it on your own system and adapting the variations above to what you actually need, so it is worth experimenting with in a safe, low-stakes situation before relying on it in a script or during troubleshooting. Keeping a note of the commands you find most useful, along with the variations that fit your workflow, turns scattered one-off tricks into a personal reference you can draw on whenever a similar task comes up again.