#PSTip Create a file of the specified size

Sometimes you need to create a file of the specified size, as a placeholder for instance. There are many utilities that do that (e.g. fsutil ) but in this tip I’ll show you how to create a file of the specified size using a .NET class.

function New-EmptyFile
{
   param( [string]$FilePath,[double]$Size )

   $file = [System.IO.File]::Create($FilePath)
   $file.SetLength($Size)
   $file.Close()
   Get-Item $file.Name
}

For example, you can use the New-EmptyFile function to create a 20 MB file:

PS> New-EmptyFile -FilePath c:\temp\test.txt -Size 20mb

    Directory: C:\temp

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/22/2012   3:39 PM   20971520 test.txt

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: