0
0
PowershellHow-ToBeginner · 2 min read

PowerShell Script to Count Lines in a File

Use (Get-Content filename.txt).Count in PowerShell to count the number of lines in a file.
📋

Examples

Inputfile content: "Hello\nWorld"
Output2
Inputfile content: "Line1\nLine2\nLine3"
Output3
Inputfile content: "" (empty file)
Output0
🧠

How to Think About It

To count lines in a file, read all lines into memory and then count how many lines were read. PowerShell's Get-Content reads the file line by line into an array, and counting the array elements gives the line count.
📐

Algorithm

1
Get the file path as input.
2
Read all lines from the file into a list.
3
Count the number of lines in the list.
4
Output the count.
💻

Code

powershell
param([string]$filePath = "sample.txt")

if (Test-Path $filePath) {
    $lineCount = (Get-Content $filePath).Count
    Write-Output "Number of lines: $lineCount"
} else {
    Write-Output "File not found: $filePath"
}
Output
Number of lines: 3
🔍

Dry Run

Let's trace counting lines in a file with 3 lines: 'Line1', 'Line2', 'Line3'.

1

Check if file exists

File 'sample.txt' exists.

2

Read file lines

Get-Content reads lines: ['Line1', 'Line2', 'Line3']

3

Count lines

Count is 3.

StepActionValue
1File exists?True
2Lines read['Line1', 'Line2', 'Line3']
3Line count3
💡

Why This Works

Step 1: Reading the file

The Get-Content command reads the file line by line into an array.

Step 2: Counting lines

Using .Count on the array returns how many lines were read.

Step 3: Outputting result

The script prints the total line count to the console.

🔄

Alternative Approaches

Using Measure-Object
powershell
$lineCount = Get-Content sample.txt | Measure-Object -Line | Select-Object -ExpandProperty Lines
Write-Output "Number of lines: $lineCount"
This method streams the file and counts lines without loading all lines into memory at once, better for large files.
Using .NET StreamReader
powershell
$count = 0
$reader = [System.IO.StreamReader]::new('sample.txt')
while ($reader.ReadLine() -ne $null) { $count++ }
$reader.Close()
Write-Output "Number of lines: $count"
This approach reads the file line by line manually, useful for very large files to reduce memory usage.

Complexity: O(n) time, O(n) space

Time Complexity

The script reads each line once, so time grows linearly with the number of lines.

Space Complexity

Using Get-Content loads all lines into memory, so space grows with file size.

Which Approach is Fastest?

Using Measure-Object streams lines and uses less memory, making it faster for large files.

ApproachTimeSpaceBest For
Get-Content with .CountO(n)O(n)Small to medium files
Get-Content with Measure-ObjectO(n)O(1)Large files
.NET StreamReader loopO(n)O(1)Very large files with minimal memory
💡
Use Get-Content filename | Measure-Object -Line for efficient line counting on large files.
⚠️
Beginners often forget to check if the file exists before counting lines, causing errors.