本日は、PowerShellでテキストファイルを分割するスクリプトについて解説します。
このPowerShellのファイル名は、「textsplit.ps1」とします。
変数は下記を使用します。
分割行数を変更したい場合は、$linesPerFileの値を変更してください。
$filePath: 分割したいテキストファイルのパスを指定します。
$outputDirectory: 分割されたテキストファイルの出力先ディレクトリのパスを指定します。
$linesPerFile: 1つのファイルに含める行数を指定します。この例では10行ごとにファイルが分割されます。
$fileNamePrefix: 分割されたファイルの接頭辞を指定します。この例では、ファイル名が”output1.txt”、”output2.txt”、”output3.txt”のようになります。
スクリプトの内容を記載します。
# 元のテキストファイルのパス
$filePath = "C:\Users\user\Desktop\textsplit\input.txt"
# 分割されたテキストファイルの出力ディレクトリ
$outputDirectory ="C:\Users\user\Desktop\textsplit"
# 1つのファイルに含める行数
$linesPerFile = 10
# ファイルのカウンター
$fileCounter = 1
# ファイル名の接頭辞
$fileNamePrefix = "output"
# ファイルを読み込み、指定した行数ごとにファイルを分割
$lines = Get-Content $filePath
$currentLine = 1
while ($currentLine -le $lines.Count) {
$currentOutputFile = Join-Path $outputDirectory "$fileNamePrefix$fileCounter.txt"
$linesToWrite = $lines[$currentLine..($currentLine + $linesPerFile - 1)]
$linesToWrite | Out-File $currentOutputFile -Encoding UTF8
$currentLine += $linesPerFile
$fileCounter++
}
Write-Host "ファイルの分割が完了しました"
スクリプトファイルの実行
デスクトップ上にtextsplit.ps1と分割したいファイル(ここではC:\Users\user\Desktop\input.txt)を準備します。
input.txtファイルの中身は100行以上あります。

textsplit.ps1を実行します。

テキストファイルは、分割されました。

分割されたファイルの中身も10行ごとに分割されています。

まとめ
本日は、PowerShellでテキストファイルを分割するスクリプトについて解説いたしました。