How to create a brunch of files with fixed size at once?

Marin Marinov 161 Reputation points
2023-11-16T16:07:32.8633333+00:00

Hi guys, for test proposes I want to create a bunch of files with fixed size. This is how far I got

(1..10) | ForEach-Object {New-Item -Name "New-File$_.txt" -ItemType File -Path ".\Test" } 

I could not figure out a way to set the size of each .txt file so I asked Google. Here is what I found:

$file = New-Object System.IO.FileStream ".\Test\New-File.txt", Create, ReadWrite
$file.SetLength(10m)
$file.Close()

Above script creates a 10mb .txt file. I`m struggling to find a way to integrate it in a loop. May I ask you for help?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Luigi Bruno 316 Reputation points Volunteer Moderator
    2023-11-16T17:37:27.3733333+00:00

    Hello Marin.

    This PowerShell snippet creates a set of 10 files of 100 Kilobytes each, giving a unique name to each file.

    For ($i=1; $i -le 10; $i++)
    {
      $FileName = "File"+$i+".txt"
      Write-Host $FileName
      $file = New-Object System.IO.FileStream $FileName, Create, ReadWrite
      $file.SetLength(100Kb)
      $file.Close()
    }
    

    You can take it as a reference.

    Bye.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Marin Marinov 161 Reputation points
    2023-11-17T15:47:22.1366667+00:00

    Hello Luigi, thank you for you answer! It helped me to write the script I needed. Here is the final result:

    Write-Host "I will create for you a bunch of files!" -ForegroundColor Yellow
    $date = Get-Date -Format dd-MM-yyyy
    $numb = Read-Host -Prompt "How many files do you want me to create?" 
    $size = Read-Host -Prompt "How big do you want to be each file?"
    
    
    For ($i=1; $i -le $numb; $i++)
    {
      $file = New-Object System.IO.FileStream  ".\Test\$date-File-[$i].txt", Create, ReadWrite
      $file.SetLength($size)
      $file.Close()
    }
    
    

    By the way, any idea how I can change the path based on user`s input ($path = Get-Host "type path")?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.