A multi-gigabyte text file can be difficult to open, transfer, or feed into another application. Splitting it into numbered files by line count makes it more manageable—and Windows PowerShell can do the job without loading the entire file into memory or changing the original.

The method below reads one line at a time and writes UTF-8 output files. It works in Windows PowerShell 5.1 and PowerShell 7 on Windows.

A computer screen shows a large text file being split into five smaller, numbered files while the original remains protected. Before you start​

You’ll need:

  • The full path to the source text file.
  • An output folder with enough free space for the resulting files.
  • Permission to read the source and create files in the output folder.
  • A line limit for each output file, such as 100,000.

Use a new or empty output folder for this run. The script refuses to overwrite an existing output file, but files created before an error will remain in the folder.

This is a line-based split, not a byte-for-byte copy. It preserves the order and text of lines when the input is decoded correctly, but it writes new line endings and converts the output to UTF-8.

Split the file​

Open Windows PowerShell from the Start menu. Copy the following block into the window, change the first three settings, and run it:

Code:
# Change these three settings.
$inputPath = 'C:\Data\large-file.txt'
$outputDirectory = 'C:\Data\split-output'
$linesPerFile = 100000

if ($linesPerFile -lt 1) {
 throw 'The line limit must be at least 1.'
}

# Create the output directory if it does not exist.
[System.IO.Directory]::CreateDirectory($outputDirectory) | Out-Null

$reader = $null
$writer = $null
$fileNumber = 0
$linesInFile = 0
$totalLines = [long]0

# The output files will be UTF-8 without a byte-order mark.
$outputEncoding = [System.Text.UTF8Encoding]::new($false)

try {
 # Defaults to UTF-8 and detects supported Unicode BOMs.
 $reader = [System.IO.StreamReader]::new($inputPath)

 while ($null -ne ($line = $reader.ReadLine())) {
 if ($null -eq $writer -or $linesInFile -ge $linesPerFile) {
 if ($null -ne $writer) {
 $writer.Dispose()
 $writer = $null
 }

 $fileNumber++
 $fileName = 'part_{0:D5}.txt' -f $fileNumber
 $outputPath = [System.IO.Path]::Combine(
 $outputDirectory,
 $fileName
 )

 # CreateNew prevents an existing file from being overwritten.
 $stream = [System.IO.FileStream]::new(
 $outputPath,
 ([System.IO.FileMode]::CreateNew),
 ([System.IO.FileAccess]::Write)
 )

 try {
 $writer = [System.IO.StreamWriter]::new(
 $stream,
 $outputEncoding
 )
 }
 catch {
 $stream.Dispose()
 throw
 }

 $linesInFile = 0
 }

 $writer.WriteLine($line)
 $linesInFile++
 $totalLines++
 }
}
finally {
 try {
 if ($null -ne $writer) {
 $writer.Dispose()
 }
 }
 finally {
 if ($null -ne $reader) {
 $reader.Dispose()
 }
 }
}

Write-Host "Finished: $totalLines lines written to $fileNumber file(s)."

For a source containing 250,000 lines and a limit of 100,000, the output will be:

  • part_00001.txt — 100,000 lines
  • part_00002.txt — 100,000 lines
  • part_00003.txt — 50,000 lines

The final file can contain fewer lines than the limit. An empty source creates no output files.

The reader processes the source incrementally, so memory use generally depends on the current line and buffers rather than the entire file. An exceptionally long individual line can still require substantial memory.

In short: The source stays intact, each new file contains at most the chosen number of lines, and an existing output filename stops the run rather than being overwritten.

Choose the right encoding​

The example assumes the source is UTF-8 unless a recognized Unicode byte-order mark, or BOM, identifies another supported encoding. Microsoft’s.NET documentation says StreamReader can detect BOM-marked UTF-8, UTF-16, and UTF-32 variants. Without a recognized BOM, it uses UTF-8.

That matters for older text files. A legacy Windows-encoded file without a BOM may be decoded incorrectly, producing replacement characters or otherwise altered text. Check the source encoding before processing important data, and inspect output containing accented characters or other non-ASCII text.

If you know the source uses a particular legacy code page, replace this line:

$reader = [System.IO.StreamReader]::new($inputPath)

For example, for a file known to use Windows-1252, use:

Code:
$inputEncoding = [System.Text.Encoding]::GetEncoding(1252)
$reader = [System.IO.StreamReader]::new(
 $inputPath,
 $inputEncoding,
 $false
)

The final $false disables BOM-based encoding detection, so use this version only when you know the file’s encoding. The output remains UTF-8 without a BOM.

If the receiving application requires a UTF-8 BOM, change the output encoding setting to:

$outputEncoding = [System.Text.UTF8Encoding]::new($true)

Microsoft documents an important Windows PowerShell distinction: version 5.1’s text-output defaults vary by cmdlet, while newer PowerShell versions generally default to UTF-8 without a BOM. The script specifies its output encoding explicitly, avoiding that particular guessing game.

Check the results​

First, confirm the files exist and inspect their sizes:

Code:
Get-ChildItem -LiteralPath $outputDirectory -Filter 'part_*.txt' |
 Sort-Object Name |
 Select-Object Name, Length

To count the lines in each output file, run the following in the same PowerShell session after the split. It also compares the output total with the count recorded during the split:

Code:
$outputTotal = [long]0

$files = Get-ChildItem -LiteralPath $outputDirectory -Filter 'part_*.txt' |
 Sort-Object Name

foreach ($file in $files) {
 $count = [long]0
 $checkReader = [System.IO.StreamReader]::new($file.FullName)

 try {
 while ($null -ne $checkReader.ReadLine()) {
 $count++
 }
 }
 finally {
 $checkReader.Dispose()
 }

 $outputTotal += $count

 [PSCustomObject]@{
 File = $file.Name
 Lines = $count
 }
}

Write-Host "Lines read from source: $totalLines"
Write-Host "Lines found in output: $outputTotal"
Write-Host "Counts match: $($totalLines -eq $outputTotal)"

Each file except the last should have the requested line count, and the totals should match. This second pass can take time on large files.

A matching count is not a full integrity check: It does not prove that every character was decoded correctly or that the content is suitable for the receiving application. Open representative files and check their first and last lines, especially around split boundaries.

Common problems and limits​

  • “The file already exists.” The output folder contains a filename the script would create. Choose a different empty folder, or carefully remove unwanted partial output before retrying.
  • Access denied. Check read permission on the source and write permission on the destination. Use an account authorized to access both rather than elevating unnecessarily.
  • Incorrect characters. Confirm the source encoding and use the appropriate reader setting. Also make sure the application opening the output recognizes UTF-8.
  • The disk fills up. Choose a destination with sufficient free space. Output size can differ from source size because encoding and line endings may change.
  • The process stops midway. Completed files and a partial current file may remain. They are not a complete result; investigate the error and rerun into a clean folder.

Finally, line splitting is not always record splitting. A CSV field can contain an embedded newline, for example, and a log entry can span multiple lines. This method may divide such records between files. Use a format-aware tool when each output must contain complete logical records.

For related WindowsForum reading, look for guides on PowerShell file handling, text encodings, and safely processing large log files.


Correction (December 3, 2026): The PowerShell samples as first published would not run. The file creation call was incomplete and did not include the CreateNew mode described in the text, and several line reading and cleanup calls were missing the parentheses PowerShell requires to run them. The samples have been corrected so they run as described and refuse to overwrite an existing output file.

 

Last edited: