Use PowerShell to split a CSV file into individual files that can be opened in Excel

Problem:

How do I use PowerShell to split a CSV file into individual files that can be opened in Excel?

Solution:

Use the PowerShell below, just change the get-content path to your file and set the line limit to your max number of rows per .csv file

$InputFilename = Get-Content 'C:\file\location\file.csv'

$OutputFilenamePattern = 'output_done_'

$LineLimit = 50000

$line = 0

$i = 0

$file = 0

$start = 0

while ($line -le $InputFilename.Length) {

if ($i -eq $LineLimit -Or $line -eq $InputFilename.Length) {

$file++

$Filename = "$OutputFilenamePattern$file.csv"

$InputFilename[$start..($line-1)] | Out-File $Filename -Force

$start = $line;

$i = 0

Write-Host "$Filename"

}

$i++;

$line++

}

Leave a Reply

Your email address will not be published. Required fields are marked *