PowerShell: Creating large dummy files with .NET

Ok, this one’s is cool i think. Whenever i needed a large dummy file, i opened up notepad, write ASDFASDFASDFA CTRL-A, CTRL-C, CTRL-V,CTRL-V,CTRL-V,CTRL-V. CTRL-A, CTRL-C, CTRL-V,CTRL-V,CTRL-V,CTRL-V,CTRL-V.. Then i saved the file, opened up a CMD-Shell and wrote copy dummyFile.txt+dummyFile.txt+dummyFile.txt until the file was large enough.. ok, there’s fsutil.exe which does the same in a much more efficient manner.. OR, unleash the Power of .NET – no, you don’t have to start programming using Visual Studio, just open up PowerShell.. Logo_PowerShell

Ok, the goal is to have a 1gb large dummy file ..

first we declare a string variable called file:

PS C:\> $file = "$env:temp\dummyFile.txt"

no we create on object of type Io.File
PS C:\> $objFile = [io.file]::Create($file)

on the object, we call the void SetLength parameterized with 1gb 
PS C:\> $objFile.SetLength(1gb)

no we call the close method and the file is written
PS C:\> $objFile.Close()

using get-item $file we list the file we just created:

PS C:\> Get-Item $file Directory: C:\Users\\AppData\Local\Temp

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        13.03.2010     14:07 1073741824 dummyFile.txt

PS C:\>

Ok, finally we can call an ii (Invoke-Item) to open the Path where the dummyFile resides in Windows Explorer.

To get the Path from a File, we can use Get-ChildItem (Get-ChildItems returns a FileInfo Object/Class). This object has a DirectoryName Property.

We declare an Object $path

$path = Get-ChildItem $file

Finally we call the mentioned ii (Invoke-Item) to open the path in Windows Explorer.

ii $path.DirectoryName

The complete Script

$file = "$env:temp\dummyFile.txt"
$objFile = [io.file]::Create($file)
$objFile.SetLength(1gb)
$objFile.Close()
$path = Get-ChildItem $file
ii $path.DirectoryName

One thought on “PowerShell: Creating large dummy files with .NET

  1. I updated the script to ask for input for the filepath and size:

    $file = Read-Host “Enter File Path”
    $size = Read-Host “Enter File Size followed by MB or GB (Example: 10MB or 10GB)”
    $objFile = [io.file]::Create($file)
    $objFile.SetLength((Invoke-Expression $size))
    $objFile.Close()
    Write-Host “File Created: $file Size: $size”

Leave a Reply

Your email address will not be published. Required fields are marked *