Create a Zero’d out File with Powershell

When sql server adds space to a transaction log file (or creates the transaction log file) it needs to zero-out said file.  Whilst zeroing out the file Sql Server is unfortunately read-only.  Hence why you need to be careful in setting reasonable transaction log growth sizes.  I wanted to get a quick fix on how long a particularly old system took to create a file and zero it out, hence this script.

$start = get-date
$File = 'c:\fileToCreate.txt'

if(Test-Path $File){
    Remove-Item $File -Force
}
 
$arrSize= 64kb
$fileSize= 1GB
$buffer = new-object byte[]($arrSize)
$stream = [io.File]::OpenWrite($File)

try{
    $size = 0
    while($size -lt $fileSize){
        $stream.Write($buffer, 0, $buffer.Length);
        $size += $buffer.Length;
    }
} 
finally{
    if($stream){
        $stream.Close();
    }
    $ts = New-TimeSpan -Start $start -End (Get-Date)
    $ts
 }

2 thoughts on “Create a Zero’d out File with Powershell

  1. You have:
    $File = ‘c:\fileToCreate.txt’
    but you open using:
    $stream = [io.File]::OpenWrite($FilePath)

    $FilePath needs to be $File or $File needs to be $FilePath for this to work.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.