В повседневной работе по той или иной причине системному администратору периодически приходится создавать файлы определенного размера. Обычно необходимость в создании файла определенного размера возникает при тестировании различных подсистем, например вы хотите протестировать работу дисковых квот или фильтров электронной почты. Самый простой способ создать файл определенного размера – воспользоваться Windows-утилитой fsutil.exe. Эта утилита командной строки, которую можно использовать для управления дисковыми квотами, различными манипуляциями с объектами файловой системы, а также для выполнения различных манипуляций с файлами.
Например, вы тестируете работу модуля статистики вашего почтового сервера, и вам нужно создать файл размером 10 Мб и отправить его по почте. Наберите в командной строке с повышенными привилегиями следующую команду:
fsutil file createnew C:\10mb-file.txt 10000000
Эта команда создаст в корне диска C:\ новый файл с именем ’10mb-file.txt’, размером 10000000 байт (10 Мб).
Иногда бывают ситуации, в которых требуется быстро создать один или несколько файлов произвольного размера. Операционная система Windows предлагает для этого несколько различных вариантов.
Создание файла с помощью fsutil
Быстрее и проще всего создать файл с помощью утилиты командной строки fsutil. Для примера откроем консоль (обязательно с правами администратора) и создадим на диске E файл file.txt размером 1ГБ командой:
fsutil file createnew E:\File.txt 1000000000
Таким образом можно создать файл любого размера, причем файл создается практически мгновенно.
Создание файла с помощью PowerShell
То же самое можно сделать с помощью PowerShell, хотя команды будут немного сложнее:
$file = New-Object -TypeName System.IO.FileStream -ArgumentList E:\File.txt,Create,ReadWrite
$file.SetLength(1000Mb)
$file.Close()
Здесь мы сначала создаем объект типа файл, а затем с помощью метода SetLength присваиваем ему необходимый размер. Таким способом также можно мгновенно создать файл любого размера.
Есть и еще один, альтернативный способ создания файла с помощью PowerShell. Если в первом случае мы создавали файл и задавали его размер, то здесь создаем содержимое нужного размера и помещаем это содержимое в указанный файл. Например:
$content = New-Object -TypeName Byte[] -ArgumentList 10Mb
Set-Content -Path E:\File.txt -Value $content -Encoding Byte
При использовании этого метода создание файла занимает некоторое время, зависящее от размера файла. Кроме того, с его помощью невозможно создать файл большого размера. Максимальный размер файла ограничен встроенным значением [int]::MaxValue и при его превышении будет выдана ошибка ″Array dimentions exceeded supported range″.
Все описанные способы создают пустые файлы (точнее файлы, заполненные символом NUL). Если надо создать файл заданного размера и заполнить его каким либо произвольным содержимым, то можно немного изменить предыдущий способ и воспользоваться такими командами:
$array = New-Object -TypeName Byte[] -ArgumentList 10Mb
$obj = New-Object -TypeName System.Random
$obj.NextBytes($array)
Set-Content -Path E:\File.txt -Value $array -Encoding Byte
Ну и для генерации большого количества файлов (напр. 1000) можно воспользоваться таким скриптом:
$array = New-Object -TypeName Byte[] -ArgumentList 10Mb
$obj = New-Object -TypeName System.Random
$obj.NextBytes($array)
for ($i=1; $i -le 1000; $i++) {
Set-Content -Path E:\File.txt$i -Value $array -Encoding Byte
}
Работает небыстро, но для ускорения можно запустить скрипт в несколько потоков.
Sometimes, to test a system (program interactions, email, filters), you need to create a file of a certain size. Windows has two standard tools for creating a custom size file.
Content
- Create file using command prompt
- Create file using PowerShell
Article in other languages:
?? – Cómo crear un archivo de tamaño específico en Windows
?? – Как создать файл определенного размера в Windows
?? – Comment créer un fichier de taille spécifique sous Windows
?? – So erstellen Sie eine Datei mit einer bestimmten Größe in Windows
?? – Hoe maak je een bestand met een specifieke grootte in Windows
Create file using command prompt
Use the fsutil command to create a file of the specified size using the Windows command prompt. The file size for this command is specified in bytes.
Create 1 MB TestFile.txt:
fsutil file createnew D:\TestFile.txt 1048576
If you get “Error: Access denied” when creating a file at the specified location – run command prompt as administrator.
Create file using PowerShell
Create empty file of specified size
To create a file of a specific size with Windows PowerShell, use the following sequence of commands (file size is specified in: Kb, Mb, Gb):
$file = New-Object -TypeName System.IO.FileStream -ArgumentList D:\TestFile.txt,Create,ReadWrite
$file.SetLength(1Mb)
$file.Close()
Windows PowerShell will create an empty file (filled with NULL characters) of the selected size.
If, when creating a file in the specified location, you receive an error: “New-Object : Exception calling “.ctor” with “3” argument(s): “Access to the path … “- run Windows PowerShell as administrator.
Create non-empty file of given size
To create a 1 MB non-empty file (random content), run the Windows PowerShell commands:
$array = New-Object -TypeName Byte[] -ArgumentList 2Mb
$obj = New-Object -TypeName System.Random
$obj.NextBytes($array)
Set-Content -Path D:\TestFile.txt -Value $array -Encoding Byte
File creation speed will depend on the specified file size and the specifications of your computer.
Create multiple files of a given size
Create 5 non-empty files (random content) 1MB in size using Windows PowerShell:
$array = New-Object -TypeName Byte[] -ArgumentList 1Mb
$obj = New-Object -TypeName System.Random
$obj.NextBytes($array)
for ($i=1; $i -le 5; $i++) {Set-Content -Path D:\Test\TestFile$i.txt -Value $array -Encoding Byte}
The speed of files creation will depend on the specified files size and the characteristics of your computer.
? How to create a file of a specific size has been discussed in this article. Now you can create a file or several files of arbitrary size for testing programs or services. However, if you run into any problems, do not hesitate to write in the comments. I will try to help.
While many everyday users might not immediately see the need to create random dummy files of a specific size, tech enthusiasts, software developers, and power users understand how valuable these files can sometimes be. Dummy files are useful for testing purposes, such as identifying bad sectors on a hard drive, measuring network speed, or ensuring that files are securely erased beyond recovery. Whatever your reasons, here are a couple of methods to create dummy files in both Windows 10 and Windows 11:
1. How to use CMD to create a file with dummy content (fsutil command)
All Windows versions since Vista include an executable named fsutil.exe. In both Windows 10 and Windows 11, you can find it in:
C:\Windows\System32
The folder containing the fsutil executable
Fsutil.exe is a powerful tool for managing partitions and volumes, and it can also be used to create dummy files of any size from the Command Prompt. If you want to launch the Command Prompt, search for cmd in the taskbar’s search field, and then click or tap Command Prompt. If you need to create files in a protected folder, such as the system drive (C:), choose to Run as administrator instead so that the Command Prompt has the required privileges to create such files for you. This is what it looks like in Windows 10:
Open Command Prompt in Windows 10
And this is what launching Command Prompt from the taskbar looks like in Windows 11:
Open Command Prompt in Windows 11
Once the Command Prompt is open on your Windows 10 or Windows 11 computer, type the command as is:
fsutil
Hit Enter and you get to see a list of commands supported by this tool. As shown in the screenshot below, there are many parameters that you can use.
The list of commands supported by fsutil
TIP: This only gives you a taste of what fsutil.exe can do. You can find complete information about its capabilities in its official documentation on TechNet.
There are two commands you can enter in the Command Prompt to create a dummy file:
fsutil file createnew filename size
or
fsutil file createnew path\filename size
Replace filename with the name you want for the dummy file. You can choose to add a file extension or not, as this does not affect the process. Replace size with the size you want your dummy file to have. The size is measured in bytes and it might be easier to use an online converter to help you define the size you prefer.
The difference between the two commands is that the second one allows you to specify exactly where your file is stored, by replacing path with a location of your choice on your device.
Now that we got over the theory part, let’s see how this works in practice. I first created a file called myfile.exe with a size of 10 MB or 10485760 bytes. To create it, I entered the following command:
fsutil file createnew myfile.exe 10485760
Creating a file using the first command
As seen above, if you use the first command and don’t specify a path, the file is created in your user profile folder. In my case, it was stored in:
C:\Users\test
I then created another 2 MB file, this time using a specific path and no extension. I entered:
fsutil file createnew D:\myfile 2097152
Creating a file using the second command
IMPORTANT: One aspect to note is that the files created with fsutil.exe are empty. There’s no content inside.
2. How to use PowerShell to create a dummy file in Windows
You can also create a dummy file using PowerShell in both Windows 10 and Windows 11. There are many ways to launch this app, yet one I find easiest is to type powershell in the taskbar’s search field, and then click or tap the Windows PowerShell result. However, if you plan to create random dummy files on your system drive (C:), make sure to select “Run as Administrator” from the options on the right. This is what it looks like in Windows 10:
Open PowerShell in Windows 10
And this is how to open PowerShell in Windows 11:
Open PowerShell in Windows 11
Then, you need to enter the following one-line command to create a dummy file in PowerShell:
$out = new-object byte[] size; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes(‘path\filename‘, $out)
Replace size with the size your dummy file should have, in bytes. You can use an online converter if you need help defining the size, especially if you want Windows to create a large file with random data. Replace path with the location where you want to create the dummy file. Replace filename with the name you want for the dummy file. Add a file extension if you want to. Let’s illustrate this with an example to make it clearer:
I decided to create a file called mypowerfile.txt with a size of 1 MB (or 1048576 bytes) on the desktop. I entered the following command to create it:
$out = new-object byte[] 1048576; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes(‘C:\Users\test\Desktop\mypowerfile.txt’, $out)
Create a dummy file using PowerShell
Although PowerShell doesn’t offer real-time feedback (unless you’ve made an error writing the command), you can tell it is done creating the file when it is ready for another command. If you go to the specified location, you can see that the dummy file has been created.
A dummy file created with PowerShell
Similar to using fsutil in the Command Prompt, you can leave out the path and the file is created in your user profile folder. I used the same command as above, leaving out the path entirely:
$out = new-object byte[] 1048576; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes(‘mypowerfile.txt’, $out)
Create a dummy file without specifying the path
Without a path, the new dummy file is stored by default at:
C:\Users\YourUserName\mypowerfile.exe
Files without a specified path are created in your user profile folder
IMPORTANT: As opposed to fsutil, which creates empty files, PowerShell lets you create fake files with randomly generated content. If you compare two files, created using the same command, you can see that they have different content.
Out of all the options in this article, PowerShell is the most complicated, both because of the complexity of its commands and the absence of confirmation when your dummy file is generated. However, power users may prefer it to the other options.
TIP: When using the PowerShell commands above, you can add a parameter that makes the console provide feedback, while creating dummy files. However, keep in mind that this makes the command unnecessarily long, as you have to insert the following one-liner:
$out = new-object byte[] 1048576; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes(‘mypowerfile.txt’, $out); if ($out -ne $null) {Write-Host («Dummy file successfully created»)} else {«Failed to create dummy file»}
3. How to create a random dummy file with a third-party fake file generator
If you want dummy files with random content, or if you are uncomfortable with the Command Prompt, then you should consider using a third-party app such as the Dummy File Creator, which is free and easy to use. When choosing how to download it, I recommend you to get the archive and extract it somewhere on your computer. Then, run the Dummy.exe file. If you want to generate files on your system drive (C:), right-click or press-and-hold and select Run as administrator, or the program will return an error when it tries to create your fake files.
Run Dummy.exe to start creating dummy files in Windows
While in need of a makeover, the interface of this program is straightforward. The Mode section lets you choose whether you want to generate one file or more. Use the Browse button to get to the location where you want to create the file(s) and type in the name (and extension, if you want one). Next, specify the File Size and check the “Random file content (non-compressible)” box if you want your file(s) to have random content. Then, click or tap Create.
Customize your dummy file(s) and press Create
A progress bar keeps you updated while your file is being created. As soon as the program finishes writing, you get a notification informing you that your file was created.
A pop-up lets you know the file was created
This tool is obviously easier to use than CMD or PowerShell to create empty files, and it also comes with several advantages, like creating more files at the same time and the option to add random file content.
Which method do you find easiest?
I searched the pits of the internet and downloaded one too many suspicious files in order to bring you this tutorial. Whichever method you choose, Windows provides multiple ways to create dummy files, whether you’re using the Command Prompt, PowerShell, or third-party tools. Let me know which method works best for you, and feel free to share any additional techniques for generating dummy files in the comments.
Sometimes you need to create a file of specific size for testing purposes. While you can try to create just a text file with some app like Notepad, it is very inconvenient when you need to create a huge file or many files at once. Here is a better solution.
Windows comes with a special console tool, fsutil. Fsutil targets advanced users and system administrators. Some that I think may be of interest are discussed. It performs tasks that are related to file allocation table (FAT) and NTFS file systems, such as managing reparse points, managing sparse files, or dismounting a volume. If it is used without parameters, Fsutil displays a list of supported subcommands. The tool is available in Windows starting in Windows XP.
You must be logged on as an administrator or a member of the Administrators group to use Fsutil. It may be necessary to enable the WSL feature to get full fsutil functionality.
One of the fsutil parameters is «file». It contains a set of subcommands which can be used to find a file by user name (if Disk Quotas are enabled), to query allocated ranges for a file, to set a file’s short name, to set a file’s valid data length, to set zero data for a file, to create a new file.
In our case, we need to use the fsutil app as follows.
To create a file of specific size in Windows 10, do the following.
- Open an elevated command prompt.
- Type or copy-paste the following command:
fsutil file createnew <filename> <length>
- Substitute the <filename> portion with the actual file name.
- Substitute <length> with the desired file size in BYTES.
The following command will create the file winaero.bin with size of 4 kilobytes under the location c:\data.
fsutil file createnew c:\data\winaero.bin 4096
Tip: Do not forget to wrap around the path to your file with quotes if it contains spaces.
See the following articles to learn more on how you can use the fsutil app:
- Enable Case Sensitive Mode for Folders in Windows 10
- How to Enable TRIM for SSDs in Windows 10
- Everything you need to know about symbolic links in Windows 10
- How to see if TRIM is enabled for SSD in Windows 10
Support us
Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:
If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!