francisco.l
francisco.l

Reputation: 336

How to create n amount of files of X size using powershell?

So, I have a folder and I'd like to create say 10 files of 150MB to test something. How can I achieve that?

Upvotes: 2

Views: 1220

Answers (1)

francisco.l
francisco.l

Reputation: 336

This is an extension of the answer given at:
How to Generate File of a determinate Size in Windows?
All that would be missing is a for loop and a max amount of files.

[IO.directory]::setCurrentDirectory($(get-location).Path) #Changes directory to current PS directory
[Int64]$size = 150MB #This allows you to set the size beforehand
[Int16]$AmountOfFiles = 10
for ($i = 0; $i -lt $AmountOfFiles; $i++) {
    $f = new-object System.IO.FileStream ".\test_$i.dat", Create, ReadWrite
    $f.SetLength($Size)
    $f.Close()
}

And lets go one by one the lines, just for fun and clarity:

[IO.directory]::setCurrentDirectory($(get-location).Path) #Changes directory to current PS directory

As explained on the previous answer, PS session has an "underlying" path used by .Net that it's not the same as the "current directory" (get-location or pwd), therefore we have to "manually" change it. That's achieved with the $(Get-Location).Path portion of the code, it will set the "underlying" path to the same path as the PSSession.
 

[Int64]$size = 150MB #This allows you to set the size beforehand
[Int16]$AmountOfFiles = 10

Self-explanatory but basically we can set the size and the amount of files we need.
The size can be anything, 1GB, 12MB, 15KB. Powershell will take care of the conversion.

for ($i = 0; $i -lt $AmountOfFiles; $i++) 

An standard for loop:

  1. It initiates a variable called i on 0 (that can also be used inside the { } of the loop).
  2. It sets the maximum amount of files allowed to be less than (-lt) the $AmountOfFiles variable, so in this case $i will reach 9 and then stop looping.
  3. After each iteration, it will increase the value of $i by one

Finally:

$f = new-object System.IO.FileStream ".\test_$i.dat", Create, ReadWrite
$f.SetLength($Size)
$f.Close()
  • The first line sets the new object that will create the "dummy" files, and will place them on the current directory and set the name to "test_#.dat" where # is the current iteration, the first one will be 0 and the last one will be 9 (test_0.dat .. test_9.dat).
  • The second line sets the "length" of the file, that means it's size, in this case it's 150MB or 157286400 bytes.
  • The last one simply stops the FileStream and creates the file.

Upvotes: 4

Related Questions