#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
Share on: