0% found this document useful (0 votes)
2 views1 page

Generating Random Files in Windows - Stack Overflow

The document discusses methods for generating random files in Windows, specifically through the use of PowerShell and the fsutil command. It includes various user-contributed scripts and techniques for creating files filled with random data, addressing both text and binary formats. The conversation highlights the importance of file size, performance considerations, and the need for randomness in file content.

Uploaded by

manobraskk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

Generating Random Files in Windows - Stack Overflow

The document discusses methods for generating random files in Windows, specifically through the use of PowerShell and the fsutil command. It includes various user-contributed scripts and techniques for creating files filled with random data, addressing both text and binary formats. The conversation highlights the importance of file size, performance considerations, and the need for randomness in file content.

Uploaded by

manobraskk
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

About Products Stack Internal Search… Log in Sign up

Home Generating Random Files in Windows Ask Question

Questions Asked 17 years, 6 months ago Modified 2 years, 9 months ago Viewed 104k times

AI Assist
Does anyone have a way to generate files of random data in Windows? I would like to generate
Tags Try Stack Overflow for Agents
50,000 small (2K) files as an example.
Verified knowledge for the agentic era
Stack Overflow for 46
windows Paste this into your AI coding assistant:
Agents

Help me join Stack Overflow for


Challenges Agents here. Read
Share Improve this question Follow [Link]
asked Feb 10, 2009 at 18:51 /[Link], then start
Chat Jeff onboarding.

Articles
Supports Claude Code, Cursor, Codex,
Users Windsurf and more.
2 Could you share with us whether you want text files or binary files? Could you also comment as to what Explore Stack Overflow for Agents
programming languages you have access to (if any)? Do you have MS Office installed? Also, not very
Companies relevant, but what version of windows are you using? – user62572 Feb 10, 2009 at 20:05

Add a comment The Overflow Blog


COLLECTIVES
Solving integration woes with a hackathon
Communities for your favorite 17 Answers Sorted by: Highest score (default)
technologies. Explore all
Collectives Featured on Meta
You can run fsutil in a batch loop to create files of any size. How we talk about ourselves (and to you)
STACK INTERNAL
Are the existing open-ended question
37 fsutil file createnew [Link] 2000 tags enough to define the scope of...

Stack Overflow for Teams is


Policy: Generative AI (e.g., ChatGPT) is
now called Stack Internal. Share Improve this answer Follow answered Feb 10, 2009 at 19:01 banned
Bring the best of human
thought and AI automation Bogdan
together at your work. 3,065 1 23 21
Community activity Last 1 hr
By continuing to use this website, you agree Stack Exchange
Try for free
can store cookies on your device and disclose information in
1953 users online
accordance with our Cookie Policy. By exiting this window,Learn more 3 Comments
default cookies will be accepted. To reject cookies, select an 6 questions
option from below. Add a comment
3 answers
Necessary cookies only Customize settings beach Over a year ago 25 comments
I just found that utility. Didn't know it existed before. [Link]/2009/01/16/…
55 upvotes
0 Reply

beach Over a year ago


Popular tags
However, it doesn't create random data. Just blank files.
.net c multithreading
51 Reply
oauth2-playground python c++
Mathias Mamsch Over a year ago
And it seems to require admin permissions. Going with the powershell.

1 Reply
Linked
Add a comment
1 Improve Powershell Performance to
Generate a Random File

One-liner in Powershell: 1 PowerShell random file generator too slow

27 $out = new-object byte[] 1048576; (new-object Random).NextBytes($out); [[Link]]::Wri Related

19 select random file from directory

This is lightning fast, compared to @user188737 solution. 0 Program for generating files?

1 Randomize files output in folder


Share Improve this answer Follow answered Sep 26, 2017 at 7:07
gwiazdorrr
4 Random file generator code?
6,399 2 32 36

1 Generate Random File Paths Java


2 Comments
6 Random File Generator (again!)
Add a comment

34 Creating random binary files


Dhiwakar Ravikumar Over a year ago
Every single file that this one liner creates is identical. Is there any way to make the content of each file 0 Batch- generating a random number of
different random numbers

2 Reply 0 Random file creater, Batch-file

Jonathan Gilbert Over a year ago


0 Create n files with random number value in
Are you sure this is the case? I tried it on my system, ran it 3 times, got 3 distinct files. The constructor for loop batch
the Random type is by default based on the system time, so perhaps if you run this multiple times in very
quick succession, you might get identical files. You could avoid this by creating a single Random object and
then reusing it for each consecutive file: $rnd = New-Object Random; once at the top, and then
Hot Network Questions
$[Link] instead of (New-Object Random).NextBytes when generating the file.
Steam installation failed steam i386
3 Reply
What's the meaning of the tethered/strangulated
Snoopy on the SMEAT/Skylab preparation mission
patch?
You can use PowerShell to generate cheap random data for your files: Can a person license their own natural
resemblance if it happens to match a celebrity's
look, or does the celebrity's right of publicity
20 Copy override?
[Byte[]] $out = @() Equalizing numbers on a circle by averaging
0..2047 | % {$out += Get-Random -Minimum 0 -Maximum 255} adjacent pairs
[[Link]]::WriteAllBytes("myrandomfiletest", $out)
1880s-set TV show scene where a teen girl is
forced to bind her breasts to pass as a boy
This uses an algorithm with a seed taken from the system clock, so don't use this for ANY serious Is there any evidence to suggest Daniel 9:24-27 is
cryptographic applications. not about Antiochus IV

Are the introduction videos of the pantheons from


In addition, be wary of the performance degradation of Get-Random when increasing the size of Age of Mythology narrated by specific characters?
the output file. More on this aspect here: Postdoc: staying or moving laterally?

How do Overwhelming Combination and Reap the


PowerShell random file generator too slow Field interact

Improve Powershell Performance to Generate a Random File Using PWM from a microcontroller to generate an
adjustable VREF for an LM393 comparator

Share Improve this answer Follow edited May 23, 2017 at 12:32 answered Sep 27, 2013 at 18:23 Examples of complete metric spaces with non-
complete set of distances
Community Bot Gerrit
1 1 891 6 13 Will creases to back cover of a passport be a
problem at immigration/check-in

Can you use PCA and Elastic Net/Lasso together or


Comments do you have to use one or the other? Are there
any use cases for using these two methods
Add a comment together?

In Exodus 3:15, is the phrase ‫ לדר דּר‬better


understood as placing emphasis on location rather
than time?
I have been using Random Data File Creator and liking it, it creates binary files (i.e. not text files)
“Does the idea that Jesus could be John the
filled with pseudo-random bits, it can quickly create very large files. To use it to create multiple Baptist, Elijah, or Jeremiah imply some form of
16 small files you would need to script it, which would be very easy given it is command line. belief in reincarnation?”

arydshln dashed lines regression since TL2024?


Share Improve this answer Follow edited Dec 25, 2015 at 11:57 answered Feb 5, 2010 at 19:20 How do supporters of 'Conditional Election'
mguassa David Waters explain their apparent redundancy of the word
4,637 2 17 20 12k 7 44 77 'election' in 1 Peter 1:2?

Can case law reach beyond statutory law

Why does this buzzer circuit emit uncontrolled


noise?
1 Comment
Where did Yoshiahu die?
Add a comment
Is this a tilting wing?

Ray Woodcock Over a year ago Odd behaviour after saving a note for a contact

There are quite a few programs and cloud tools of this nature: Does the Buddhist precept against false speech
[Link]/2021/08/21/dummy-files require silence when telling the truth would cause
harm?
0 Reply
GBC compatible balls

Question feed
Since you don't specify a language, I'll simply pick one at random. Here is a powershell script to do
it:
9
$rootDir = 'C:\Temp\TestRandomFiles\'
$baseFile = $rootDir + "[Link]"
$desiredFileSize = 2*1KB
$fileCount = 50000
"start" | Out-File -Filepath $baseFile
While ($(Get-ChildItem -path $baseFile).Length -lt $desiredFileSize)
{
$(Get-ChildItem -path $baseFile).Length | Out-File $baseFile -APPEND
}
for($i=1;$i -lt $fileCount;$i++)
{
Copy-Item $baseFile "File$[Link]"
}

You'll have to change the variables to the parameters that you want of course.

Share Improve this answer Follow answered Feb 10, 2009 at 19:47
EBGreen
38.1k 12 70 86

4 Comments
Add a comment

EBGreen Over a year ago


oops...missed the random data requirement. Is that important? If so I can tweak it.

1 Reply

Wil Over a year ago


If you are a PS whiz, I don't suppose you can do random data as I am keen to learn how this done!

1 Reply

EBGreen Over a year ago


I'm definitely not a whiz, but there are several ways. Basically you identify the data set that you want to
randomize (say 0-9 and a-Z) then you randomly pick from that set to build the data for the file, then write it
out to the file. If I have a chance later today, I'll alter the above code to use random data.

0 Reply

Gennady G Over a year ago


@EBGreen thank You much! Best regards

0 Reply

Add a comment

Instead of using Get-Random to generate the text as per user188737 & mguassa suggestions, I
improved the speed by using GUIDs.
5
Function New-RandomFile {
Param(
$Path = '.',
$FileSize = 1kb,
$FileName = [guid]::NewGuid().Guid + '.txt'
)
(1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().G
}

This took 491 milliseconds to generate a 1mb file. Running:

New-RandomFile -FileSize 1mb

UPDATE:

I've updated my function to use a ScriptBlock, so you can replace the 'NewGuid()' method with
anything you want.

In this scenario, I make 1kb chunks, since I know I'm never creating smaller files. This improved the
speed of my function drastically!

Set-Content forces a NewLine at the end, which is why you need to remove 2 Characters each time
you write to file. I've replaced it with [[Link]]::WriteAllText() instead.

Function New-RandomFile_1kChunks {
Param(
$Path = (Resolve-Path '.').Path,
$FileSize = 1kb,
$FileName = [guid]::NewGuid().Guid + '.txt'
)

$Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu


[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu

$Chunks = [math]::Ceiling($FileSize/1kb)

[[Link]]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chun

Write-Warning "New-RandomFile: $Path\$FileName"

If you dont care that all chunks are random, you can simply Invoke() the generation of the 1kb
chunk once.. this improves the speed drastically, but won't make the entire file random.

Function New-RandomFile_Fast {
Param(
$Path = (Resolve-Path '.').Path,
$FileSize = 1kb,
$FileName = [guid]::NewGuid().Guid + '.txt'
)

$Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu


[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
[guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Gu
$Chunks = [math]::Ceiling($FileSize/1kb)
$ChunkString = $[Link]()

[[Link]]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chun

Write-Warning "New-RandomFile: $Path\$FileName"

Measure-Command all these changes to generate a 10mb file:

Executing New-RandomFile: 35.7688241 seconds.

Executing New-RandomFile_1kChunks: 25.1463777 seconds.

Executing New-RandomFile_Fast: 1.1626236 seconds.

Share Improve this answer Follow edited Apr 3, 2017 at 23:04 answered Apr 1, 2017 at 2:39
Marc Kellerman
466 4 10

Comments
Add a comment

None of the answers here were cutting it for me, so here's a script which takes advantage of the
Cryptography library to generate lots of random files.
3
This will generate files very quickly until your system's entropy is exhausted (on my PC this was
about 4,000 files). After this it (and any other applications on your system that need cryptographic
random numbers) will run very slowly. (In Linux terms, consider this script to use /dev/random
instead of /dev/urandom )

Copy

$directory = (Get-Location).Path;
0..10000 | ForEach-Object {
$size = 1023 * (Get-Random -Minimum 10 -Maximum 1536);
$contents = [Byte[]]::new($size);

$rng = [[Link]]::new();
$[Link]($contents);

$filename = "$directory\random$($_.ToString().PadLeft(5, '0')).txt"


Write-Host $filename
[[Link]]::WriteAllBytes($filename, $contents)
}

If you'd rather not deplete your system's entropy, replace the two $rng lines with these:

Copy

$rng = [[Link]]::new();
$[Link]($contents);

This will run much slower, but for large quantities of files (or larger files) it should be more reliable.

Share Improve this answer Follow answered Apr 15, 2020 at 0:57
Yoshi Walsh
2,137 5 27 53

Comments
Add a comment

You'll have to create files in the normal way, and then populate them with randomized data,
probably from a rand() function of some sort.
2
It really depends on your programming language. Windows itself certainly won't provide this
capability.

There are a number of programming languages that could do this easily, however, including basic
windows batch/CMD scripts. What language are you interested in using?

Share Improve this answer Follow answered Feb 10, 2009 at 18:54
levand
8,530 4 44 56

Comments
Add a comment

So, i decided to add an accurate answer this time.

language is powershell. assumptions: filenames will be sequential and not random. file contents
2
are to be cryptographically secure and unique. file location to be C:\temp\

#create a fixed size byte array for later use. make it the required file size.
$bytearray = New-Object byte[] 2048

#create and start a stopwatch object to measure how long it all takes.
$stopwatch = [[Link]]::StartNew()

#create a CSRNG object


$RNGObject = New-Object [Link]

# set up a loop to run 50000 times


0..49999 | Foreach-Object {

# create a file stream handle with a name format 'filennnnn'


$stream = New-Object [Link]("c:\temp\file$("{0:D5}" -f $_)"), Creat

# and a stream writer handle


$writer = New-Object [Link]($stream)

# Fill our array from the CSRNG


$[Link]($bytearray)

# Append to the current file


$[Link]($bytearray)

# Close the stream


$[Link]()

# how long did it all take?


$[Link]()
$stopwatch

And the output:

IsRunning Elapsed ElapsedMilliseconds ElapsedTicks


--------- ------- ------------------- ------------
False 00:07:53.7685350 473768 1434270755

Mmm, it feels like it took a long time, but

$[Link]/50000
9.47536

so, thats about 10ms per file. Thats to an old sata disk.

Share Improve this answer Follow answered Jun 18, 2018 at 13:59
psomatic
21 2

1 Comment
Add a comment

Cake Princess Over a year ago


This worked perfectly for me! Totally underrated and underrecognized. This should be the real solution!!

0 Reply

Yes, fsutil is great, but doesn't generate random data, just ASCII nulls.

I don't remember where I found this but searching on google these days I can still find it at:
1
[Link]

I don't know how old this program is but at least as old as your question, probably somewhat
older.

Anyway here's a program in C which creates files with a chi-squared test result of 0:

// ------------------------------------------------------------
// Name: random.c (program to create random files)
//
// This "no-frills" program creates files with the following
// characteristics:
//
// (1) Byte sequences are random (no predictability);
// (2) Files produced are binary files;
// (3) File sizes are multiples of 256;
// (4) Files will have a chi-squared test result of 0
// (see [Link] by Wenger for explanation)
//
// Programmer: Scott Wenger
// Box 802
// Stevens Point, WI 54481
// panther@[Link]
//
// Note: part of this code is from Knuth Volume II
//
// Enhancements and modifications of this program are left
// to the imagination and creativity of the programmer.
// Check your compiler for required header files. You may
// need to include the iostream header.
//
// Random files are of potential use to cryptographers
// for the purpose of encryption.
//
// To analyze files produced by this program, see
// the [Link] program by Scott Wenger (found at
// [Link]
// ------------------------------------------------------------

// This program works in the following way:

Share Improve this answer Follow answered Aug 10, 2016 at 13:38
Rubenisme
906 1 9 19

Comments
Add a comment

for those who found this looking for a way to overwrite unused space on drive with random data,
the following command in cmd will do:
1
cipher /w:X:\

substitute X with your drive letter

it will first write 0x00's then 0xFF's then random data on the unallocated space (leaving the files
alone). it takes some time.

Share Improve this answer Follow edited Dec 6, 2022 at 13:45 answered Dec 6, 2022 at 13:38
robotik
2,037 1 22 26

Comments
Add a comment

Well, technically you could write something to do this for you.


I don't know of anything specific.. but the easiest way would be to create a TEXT file of a specific
0 size (2K for example).. then write a batch file to copy it 50000 times.

Share Improve this answer Follow answered Feb 10, 2009 at 18:54
jgallant
11.3k 2 42 72

Comments
Add a comment

How about something like this: Random File Generator 1.1

Or File generator
0
Share Improve this answer Follow answered Feb 10, 2009 at 19:00
beach
8,720 4 34 26

1 Comment
Add a comment

EBGreen Over a year ago


Well, if that becomes the accepted answer, then it wasn't much of a programming question.

1 Reply

You could use VBA in excel if you have limited permissions on the machine that you are on. This
would create txt files to the number required with random numbers. Probably not the quickest of
0 ways of going about this though.

Sub rndcreate()

[Link] = False
[Link] = False

Dim sbook As Workbook


Dim i As Double
Dim upperbound, lowerbound, totalentries, totalfiles As Integer
Dim x, folder, file As String

'Set output location

folder = "C:\test\"

'Number of files created and entries in files as below

totalfiles = 1
totalentries = 150
upperbound = 99999
lowerbound = 1

For p = 1 To totalfiles

'Add new workbook to populate with data

Set sbook = [Link]

'Set file name

file = "randomdatafile" & p

For i = 1 To totalentries

'Randomly created integers between your two bounds

Share Improve this answer Follow answered Apr 11, 2017 at 11:56
Crellin
1 2

Comments
Add a comment

edit

I re-read the question, the following will not provide the answer (50x2k files) as is, but will create
0
arbitrarily sized files with truly random binary data.

Please comment if you would like to see an example that answers the question exactly.

/edit

The following can generate a 1GB file of cryptographically secure random data using objects
available in powershell:

#set the size, 1024^3 = 1GB


$size=1024*1024*1024

#as we will build the file 1k at a time, divide required size by 1k


$size/=1024

#now create the byte array of a fixed size


$bytearray=new-object byte[] 1024

#and create a CSRNG object


$RNGObject=new-object [Link]

#Create a file for streaming. PS will overwrite if it exists.


#its probably bad form to hard code the filename, an exercise for you
$stream = New-Object [Link]("d:\[Link]"), Create

#open the stream and grab the handle.


$writer = New-Object [Link]($stream)

#create a timer object so we can measure the runtime. start it.


$stopwatch=[[Link]]::startnew()

#now, iterate through the required file size 1k at a time


0..($size-1) | Foreach-Object{
#filling our byte array with random non zero bytes
$[Link]($bytearray)
#and them append them to the file stream.
$[Link]($bytearray)
}

#captain obvious
$[Link]()
$[Link]()

#and display the stopwatch data

To use random data with zero values, just replace

$[Link]($bytearray)

with

$[Link]($bytearray)

A quick intro to duckduckgo, if you go to [Link] and search with

!msdn [Link]

you will be given extremely focussed results direct from the Microsoft Developer Network,
allowing you to see the Crypto classes, methods and properties available.

Share Improve this answer Follow edited Jun 18, 2018 at 13:13 answered Jun 18, 2018 at 12:37
psomatic
21 2

Comments
Add a comment

Well, a bit late, but this is my contribution to a problem that will always be actual.

The way it works is self-explained in the code:


0
There are two loops. The outer one, running on the $j counter creates folders in the root of some
given $currdrive letter. The inner loop generates $i files of $size (default 1GB)

$currdrive="G"
for ($j=0;$j -lt 5;$j++){
new-item "$($currdrive):\random$($j)" -itemType directory
for ($i=0;$i -lt 100;$i++){
echo "Creating file $i...";
$size=1048576*1024;
$out = new-object byte[] $size;(new-object Random).NextBytes($out);[[Link]]
}
}

Share Improve this answer Follow answered Dec 29, 2020 at 11:47
Daniel J.
397 2 12

Comments
Add a comment

This one is fun because it generates nested folders as well:

0 $rng = [[Link]]::new();
$total = 100
0..$total | % {
$p = $(Join-Path $pwd ("$_".ToCharArray() -join '/')) + ".txt"
$d = [[Link]]::GetDirectoryName($p)
New-Item -ItemType Directory -Path $d -ErrorAction SilentlyContinue | Out-Null
$size = 1023 * (Get-Random -Minimum 1 -Maximum 512);
$contents = [Byte[]]::new($size);
$[Link]($contents);
Set-Content -Force -Path $p -Value $contents
if (($_%10) -eq 0) { Write-Host -NoNewline "$(($_/$total)*100)% " }
}; echo ""

Share Improve this answer Follow answered Oct 24, 2023 at 19:29
Jonathan DeMarks
2,449 2 16 14

Comments
Add a comment

Your Answer

Sign up or log in Post as a guest


Name

Sign up using Google


Email
Required, but never shown

Sign up using Email and Password

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our
Post Your Answer
privacy policy.

STACK OVERFLOW BUSINESS COMPANY STACK OVERFLOW’S OPEN COMMUNITIES

Questions Stack Internal About Technology


Help Stack Data Licensing Press Culture & recreation
Chat Stack Ads Work Here Life & arts
Legal Science
Privacy Policy Professional
Terms of Service Business
Contact Us
API
Cookie Settings
Data
Cookie Policy

Blog Facebook Twitter LinkedIn Instagram


Site design / logo © 2026 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2026.8.11.45024

You might also like