PowerShell: Creating large dummy files with .NET
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\<removed>\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
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”