Windows PowerShell: creating large files on disk — fast!

A co-worker of mine needed something that will create very large sequential files that contains null values — he needed to pre-allocate MongoDB space.

So I started writing a PowerShell script for him to create them (something simple that will accept parameters). At first I created something that will create the files and write nul data inside. The problem was that it just worked too slow. It took me a while to find the correct answer to do so (I admit — not a PowerShell expert).

This is what I eventually (after a lot of searching) came up with:

Write-Host "Creating files..."
$fileSize = 2146435072
for ($i = 1; $i -le $fileCount; $i++) {
$outputFileName = "$fileName.$i"
Write-Host "Writing $outputFileName ($i/$fileCount)"

$file = [System.IO.File]::Create($outputFileName)
Write-Host "Done!"

Works very fast.