Windows command line create temp file

How can I create an empty file at the DOS/Windows command-line? I tried: copy nul > file.txt But it always displays that a file was copied. Is there another method in the standard cmd? It shoul...

Without redirection, Luc Vu or Erik Konstantopoulos point out to:

copy NUL EMptyFile.txt
copy /b NUL EmptyFile.txt

«How to create empty text file from a batch file?» (2008) also points to:

type NUL > EmptyFile.txt
# also
echo. 2>EmptyFile.txt
copy nul file.txt > nul # also in qid's answer below
REM. > empty.file
fsutil file createnew file.cmd 0 # to create a file on a mapped drive

Nomad mentions an original one:

C:UsersVonCprogtests>aaaa > empty_file
'aaaa' is not recognized as an internal or external command, operable program or batch file.

C:UsersVonCprogtests>dir

 Folder C:UsersVonCprogtests

27/11/2013  10:40    <REP>          .
27/11/2013  10:40    <REP>          ..
27/11/2013  10:40                 0 empty_file

In the same spirit, Samuel suggests in the comments:

the shortest one I use is basically the one by Nomad:

.>out.txt

It does give an error:

'.' is not recognized as an internal or external command

But this error is on stderr. And > only redirects stdout, where nothing have been produced.
Hence the creation of an empty file.
The error message can be disregarded here. Or, as in Rain’s answer, redirected to NUL:

.>out.txt 2>NUL

(Original answer, November 2009)

echo.>filename

(echo "" would actually put «» in the file! And echo without the ‘.’ would put «Command ECHO activated» in the file…)

Note: the resulting file is not empty but includes a return line sequence: 2 bytes.


This discussion points to a true batch solution for a real empty file:

 <nul (set/p z=) >filename

 dir filename
 11/09/2009  19:45                 0 filename
 1 file(s)                         0 bytes

The «<nul» pipes a nul response to the set/p command, which will cause the
variable used to remain unchanged. As usual with set/p, the string to the
right of the equal sign is displayed as a prompt with no CRLF.

Since here the «string to the right of the equal sign» is empty… the result is an empty file.


The difference with cd. > filename (which is mentioned in Patrick Cuff’s answer and does also produce a 0-byte-length file) is that this «bit of redirection» (the <nul... trick) can be used to echo lines without any CR:

<nul (set/p z=hello) >out.txt
<nul (set/p z= world!) >>out.txt
dir out.txt

The dir command should indicate the file size as 11 bytes: «helloworld!«.

March 31st, 2016

Summary: Microsoft Scripting Guy Ed Wilson talks about using Windows PowerShell 5.0 on Windows 10 to create temporary files in the temporary folder.

Sometimes it is the little things that make life easier. You know, like a cereal bar … it’s not like a major technological breakthrough but it is much more convenient than getting a bowl of milk and opening a box of cereal and dumping it in the bowl. Or a peanut butter cup is easier to use than getting two bars of chocolate and a jar of peanut butter … neater too.

Well in Windows PowerShell 5.0 there are lots of these stealth features that make life easier and simpler for me than even Windows PowerShell 4.0. I am talking about Windows PowerShell 5.0 on Windows 10, because the downlevel package will not have all the API’s available for some of these way cool cmdlets.

Creating a temporary file in the temp folder

From time to time, I need to create a temporary file. In the old days I would create a file and give it a name that I would calculate. This wasn’t random, but it worked pretty good if I tested to ensure that the file did not already exist, and if it did exist, then I would delete it and create the file. As you might surmise, that was about three lines of code … not as bad as in the VBScript days, but still it was boring to do. I even wrote my own create a temporary file function to relieve some of the tedium.

Later, I was reading through the .NET Framework SDK and I came across a static method of the System.IO.Path class. It was called GetTempFileName. This was a bit confusing because at first everytime I called it to get a temporary file name, and then I used that temporary file name to create a temporary file, I would get an error … the call worked, but it generated an error. Later, I figured out that the GetTempFileName static method was actually misnamed, and should have been named CreateTempFile because that is what it does. I generates the temp file name AND creates the temporary file. So when I was calling the method to get the temp file name it created the file. Then when I attempted to use the temp file name to create the file … well an error occurred.

The really easy to create a temp file using PowerShell 5

The really easy to create a temp file is to use Windows PowerShell 5.0 on Windows 10 … because there is a New-TemporaryFile cmdlet. This is really simple:

PS C:> New-TemporaryFile

Directory: C:UsersmredwAppDataLocalTemp

Mode                LastWriteTime         Length Name

—-                ————-         —— —-

-a—-        3/31/2016   8:05 PM              0 tmp36BB.tmp

Of course, this does not do a whole lot of good because while I have a temp file, I cannot really access it very easily because I don’t know the name and path. Well, I can figure out the path perhaps, but not the file name. So the better way to do this is to capture the output. This appears here:

PS C:> $tmp = New-TemporaryFile

$tmp | fl *

PSPath            : Microsoft.PowerShell.CoreFileSystem::C:UsersmredwAppDataLocalTemptmpBADC.tmp

PSParentPath      : Microsoft.PowerShell.CoreFileSystem::C:UsersmredwAppDataLocalTemp

PSChildName       : tmpBADC.tmp

PSDrive           : C

PSProvider        : Microsoft.PowerShell.CoreFileSystem

PSIsContainer     : False

Mode              : -a—-

VersionInfo       : File:             C:UsersmredwAppDataLocalTemptmpBADC.tmp

InternalName:

OriginalFilename:

FileVersion:

FileDescription:

Product:

ProductVersion:

Debug:            False

Patched:          False

PreRelease:       False

PrivateBuild:     False

SpecialBuild:     False

Language:

BaseName          : tmpBADC

Target            : {}

LinkType          :

Name              : tmpBADC.tmp

Length            : 0

DirectoryName     : C:UsersmredwAppDataLocalTemp

Directory         : C:UsersmredwAppDataLocalTemp

IsReadOnly        : False

Exists            : True

FullName          : C:UsersmredwAppDataLocalTemptmpBADC.tmp

Extension         : .tmp

CreationTime      : 3/31/2016 8:07:31 PM

CreationTimeUtc   : 4/1/2016 12:07:31 AM

LastAccessTime    : 3/31/2016 8:07:31 PM

LastAccessTimeUtc : 4/1/2016 12:07:31 AM

LastWriteTime     : 3/31/2016 8:07:31 PM

LastWriteTimeUtc  : 4/1/2016 12:07:31 AM

Attributes        : Archive

More than likely, I want the fullname property because it contains the path to the file as well as the file name and extension. It will be easy to use. This appears here:

PS C:> $tmp.FullName

C:UsersmredwAppDataLocalTemptmpBADC.tmp

So, now I can use Out-File to write to the file. This appears here:

Get-Process | Out-File $tmp.FullName

notepad $tmp.FullName

Or, I can redirect to the file. This appears here:

Get-Service >> $tmp.FullName

notepad $tmp.FullName

Remove-Item $tmp.FullName -Force

When I am done, I want to use Remove-Item to delete the temporary file so that I keep things neat and tidy.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. Also check out my Microsoft Operations Management Suite Blog. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

What is the best way to create an empty file from the command line in windows?

I have been using the touch command but it isn’t in stock windows.

One idea was to use echo . >file that works, but the file is never really empty that way. Is there a way to generate an empty file similar to what touch file would do using only what comes with stock windows.

asked Apr 19, 2011 at 22:05

sylvanaar's user avatar

Community's user avatar

answered Apr 19, 2011 at 22:12

ChrisF's user avatar

ChrisFChrisF

41.1k17 gold badges97 silver badges152 bronze badges

echo. 2> file

Give that one a try

answered Apr 19, 2011 at 22:12

Sandeep Bansal's user avatar

Sandeep BansalSandeep Bansal

6,3241 gold badge28 silver badges34 bronze badges

6

copy con file [Enter]
[F6] (or [Ctrl-Z]) [Enter]

:)

answered Apr 19, 2011 at 23:09

Ƭᴇcʜιᴇ007's user avatar

Ƭᴇcʜιᴇ007Ƭᴇcʜιᴇ007

111k19 gold badges198 silver badges262 bronze badges

1


Download Article


Download Article

Learning how to do simple file management at the Command Prompt (cmd) comes in handy when you’re learning to code. When you create files and folders at the command line, you can access, use, and manipulate those folders and files in Windows apps. We’ll show you how to create folders (directories) and text files at the Windows Command Prompt, and teach you commands for deleting unneeded files and folders.

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 10

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 11

    2

    Go to the directory in which you want to create the file. The prompt will open to C:UsersYourName by default. If the directory is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[1]

    • For example, if you want to create a file on the Desktop, type cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).

    Advertisement

  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 12

    3

    Create an empty file. If you don’t want to create an empty file, skip to the next step.[2]
    To create an empty file:

    • Type type nul > filename.txt.
    • Replace filename.txt with whatever you want to call your new file. The «.txt» part indicates that this is a plain text file. Other common file extensions include «.docx» (Word document), «.png» (empty photo),and «.rtf» (rich text document). All of these file types can be read on any Windows computer without installing additional software.
    • Press Enter.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 13

    4

    Create a file containing certain text. If you don’t want to create a file with certain text inside, skip to the next step.[3]
    Use these steps to create a plain text file that you can type into:

    • Type copy con testfile.txt, but replace testfile with the desired file name.[4]
    • Press Enter.
    • Type some text. This is a rudimentary text editor, but it’s good for quick notes or code. You can use the Enter key to go to the next line.
    • Press Control + Z when you’re finished editing the file.
    • Press the Enter key. You’ll see «1 file(s) copied,» which means your file is now saved with the name you created.
    • Another way to do this is to run this command: echo enter your text here > filename.txt.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 14

    5

    Create a file that’s a certain size. If you don’t want to create a file that’s a specific size, skip this step.[5]
    To create a blank text file based on byte size, use this command:

    • fsutil file createnew filename.txt 1000.
    • Replace filename with the desired file name, and 1000 with the actual number of bytes you’d like the file to be.
  6. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 15

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 16

    2

    Go to the directory containing the file you want to delete. The prompt will open to C:UsersYourName by default. If the file is somewhere else, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a file from the Desktop, type cd desktop and press Enter.
    • If the directory you want to view isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 17

    3

    Type dir and press Enter. This displays a list of all files in the current directory. You should see the file you want to delete in this list.

    • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 18

    4

    Type del filename and press Enter. Replace filename with the full name and extension of the file you want to delete.[6]
    File names include file extensions (e.g., *.txt, *.jpg). This deletes the file from your computer.

    • For example, to delete a text file entitled «hello», you would type del hello.txt into Command Prompt.
    • If the file’s name has a space in it (e.g., «hi there»), you will place the file’s name in quotations (e.g., del "hi there").
    • If you get an error that says the file cannot be deleted, try using del /f filename instead, as this force-deletes read-only files.
  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 1

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[7]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 2

    2

    Go to the directory in which you want to create the new directory. The prompt will open to C:UsersYourName by default. If you don’t want to create a new directory here, type cd path_to_directory and press Enter. Replace path_to_directory with the actual directory location.[8]

    • For example, if you want to create a directory on your Desktop, you would type in cd desktop and press Enter.
    • If the directory you’re looking for isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 3

    3

    Type mkdir NameOfDirectory at the prompt. Replace NameOfDirectory with the name of the directory you wish to create.[9]

    • For example, to make a directory named «Homework», you would type mkdir Homework.
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 4

    4

    Press Enter. This runs the command to create a folder with the desired name.

  5. Advertisement

  1. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 5

    1

    Open the Command Prompt. The easiest way to do this is to press Win + S to activate the search bar, type cmd, and then click Command Prompt in the search results.[10]

  2. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 6

    2

    Go to the folder containing the directory you want to delete. The prompt will open to C:UsersYourName by default. If the directory you want to delete is somewhere else, type cd path_to_directory and press Enter.[11]
    Replace path_to_directory with the actual directory location.

    • For example, if you want to delete a directory from your Desktop, type cd desktop.
    • If the directory isn’t in your user directory (e.g., C:UsersYourName), you’ll have to type in the whole path (e.g., C:UsersSomeoneElseDesktopFiles).
  3. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 7

    3

    Type rmdir /s DirectoryName. Replace DirectoryName with the name of the directory you want to delete.[12]

    • For example, if you’re trying to delete your «Homework» folder, you’d type in rmdir /s Homework here.
    • If the directory’s name has a space in it (e.g., «Homework assignments»), place the name in quotations (e.g., rmdir /s "Homework assignments").
  4. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 8

    4

    Press Enter to run the command.[13]

    • If you try to delete a directory that contains hidden files or directories, you’ll see an error that says «The directory is not empty.» In this case, you’ll have to remove the «hidden» and «system» attributes from the files inside the directory. To do this:[14]

      • Use cd to change into the directory you want to delete.
      • Run dir /a to view a list of all files in the directory and their attributes.
      • If you’re still okay with deleting all of the files in the directory, run attrib -hs *. This removes special permissions from the undeletable files.
      • Type cd .. and press Enter to go back one directory.
      • Run the rmdir /s command again to delete the folder.
  5. Image titled Create and Delete Files and Directories from Windows Command Prompt Step 9

    5

    Press y and then Enter to confirm. This will permanently remove the directory.[15]

  6. Advertisement

Add New Question

  • Question

    How can I create directories?

    Subhodeep Roy

    Subhodeep Roy

    Community Answer

    If you are creating a directory in C drive, the command will be»C:MD {the name of the directory/folder}» then press Enter.

  • Question

    How do I create a folder using CMD?

    Community Answer

    Navigate to where you want the subfolder created and type «mkdir «.

  • Question

    How do I create a test file under the sub folder?

    Community Answer

    Change directory into the new sub folder and then on the next line, create your new test file. For example: cd mysubfolder $ type nul > newtextfile.txt

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

Thanks for submitting a tip for review!

  • Using Command Prompt to delete files results in the files being deleted permanently rather than being moved to the Recycle Bin. Exercise caution when deleting files via Command Prompt.

Advertisement

About This Article

Article SummaryX

1. Use the mkdir command to create a folder.
2. Use rmdir /s to delete a folder.
3. Use the copy con or echo command to create a file.
4. Use del to delete a file.
For tips on how to create a file inside a folder, read on!

Did this summary help you?

Thanks to all authors for creating a page that has been read 1,203,184 times.

Is this article up to date?

Содержание

  1. Create file from command line
  2. To create file using echo
  3. To create file using fsutil
  4. Limitations
  5. Creating and Using a Temporary File
  6. Вывод списка временных файлов с заданным расширением в папке + возможность удаления временных файлов по имени
  7. How to create a unique temporary file path in command prompt without external tools? [duplicate]
  8. 3 Answers 3
  9. Как создать пакетный файл BAT для выполнения в командной строке CMD
  10. Что такое BAT файл?
  11. В чем польза BAT файла?
  12. Режимы BAT файла
  13. Как запустить BAT файл в Windows 10?
  14. Как создать BAT файл?
  15. Основы создания BAT файлов
  16. Руководство по созданию BAT файла

Create file from command line

We can create files from command line in two ways. The first way is to use fsutil command and the other way is to use echo command. If you want to write any specific data in the file then use echo command. If you are not bothered about the data in the file but just want to create a file of some specific size then you can use fsutil command.

To create file using echo

To create file using fsutil

Limitations

Fsutil can be used only by administrators. For non-admin users it throws up below error.

Thank you for the quick and dirty method since windows seems to lack the “touch” command.

How can we use these commands to ‘touch’ a file. Could anyone provide the exact command that can work as linux ‘touch’ for any type of file?

Windows does not lack “touch”. It is echo. As the post describes? type: echo “” Blah.cpp

dude, this isnt working on our school’s computers, can you tell another method that works on windows 8 computers please?

lmao it works at school PC

Make sure that you are typing in the code the right way. It happened to me when I typed in “echo This is a sample text file sample.txt”.

If you want to create a file with NO text in it do this:
at the CLI type “Echo.”: Your output should look like this:
C:Temp>echo.

To write to a file:
C:Temp> Echo. >test.txt

This will create a file with single space in the file.

Creating and Using a Temporary File

Applications can obtain unique file and path names for temporary files by using the GetTempFileName and GetTempPath functions. The GetTempFileName function generates a unique file name, and the GetTempPath function retrieves the path to a directory where temporary files should be created.

The following procedure describes how an application creates a temporary file for data manipulation purposes.

To create and use a temporary file

  1. The application opens the user-provided source text file by using CreateFile.
  2. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.
  3. The application reads blocks of text data into a buffer, converts the buffer contents to uppercase using the CharUpperBuffA function, and writes the converted buffer to the temporary file.
  4. When all of the source file is written to the temporary file, the application closes both files, and renames the temporary file to «allcaps.txt» by using the MoveFileEx function.

Each of the previous steps is checked for success before moving to the next step, and a failure description is displayed if an error occurs. The application will terminate immediately after displaying the error message.

Note that text file manipulation was chosen for ease of demonstration only and can be replaced with any desired data manipulation procedure required. The data file can be of any data type, not only text.

The GetTempPath function retrieves a fully qualified path string from an environment variable but does not check in advance for the existence of the path or adequate access rights to that path, which is the responsibility of the application developer. For more information, see GetTempPath. In the following example, an error is regarded as a terminal condition and the application exits after sending a descriptive message to standard output. However, many other options exist, such as prompting the user for a temporary directory or simply attempting to use the current directory.

The GetTempFileName function does not require that the GetTempPath function be used.

The following C++ example shows how to create a temporary file for data manipulation purposes.

Вывод списка временных файлов с заданным расширением в папке + возможность удаления временных файлов по имени

нужна создать bat ) я вообще бум-бум

Создайте командный файл, выполняющий вывод списка временных файлов с за-
данным расширением файла в папке с именем имя-папки, а также может удалять времен-
ные файлы с заданным именем.

В качестве первого (обязательного) параметра должно быть задано имя папки (для
текущей папки задается символ «.»). Вторым (необязательным) параметром является
расширение файла:
• bak – для временных файлов с расширением .bak;
• tmp – для временных файлов с расширением .tmp.

Если второй параметр не задан, выводится список всех временных файлов (с рас-
ширениями .bak и .tmp).

Если временные файлы в папке не найдены, выполнение командного файла закан-
чивается и выдается сообщение «В папке имя-папки нет временных файлов», в

противном случае выдается список временных файлов (с помощью цепочки команд dir и

findstr) и количество временных файлов в папке заданного типа в папке или общее ко-
личество временных файлов.

После вывода списка выдается запрос на возможность удаления временного файла
или файлов. Если ответ на запрос n, выполнение командного файла заканчивается. Если
ответ y, выводится запрос на ввод имени удаляемого файла (без расширения). Если для
значения второго параметра bak существует файл с заданным именем и расширением
.bak, он удаляется. Аналогично для значения второго параметра tmp удаляется файл с
заданным именем и расширением .tmp. Если второй параметр не задан, удаляется файл с
заданным именем и расширением .bak и/или .tmp.

Если задано удаление временных файлов, то после его окончания должно быть вы-
ведено сообщение «Удален файл/файлы с именем имя-файла».

How to create a unique temporary file path in command prompt without external tools? [duplicate]

I am trying to create the path to a temporary file to be used in a batch file.

There are the environment variables %TEMP% and %TMP% to get the temporary directory for the current user. But how to build a file name that does surely not yet exist?

Of course I can use the built-in variable %RANDOM% and create something like bat

%RANDOM%.tmp , but this method does not ensure that the file is currently inexistent (or that it will be created coincidentally by another application, before I first create it on disk and write to it) — although this all is very unlikely.

I know I could just reduce the probability of such collisions by appending also %DATE% / %TIME% , or by just adding multiple %RANDOM% instances, but this is not what I want.

Note: According to this post, there is a method in .NET ( Path.GetTempFileName() ) which does exactly what I am asking for (besides the wrong programming language obviously).

3 Answers 3

Try next code snippet:

or create procedures

    :uniqGet : create a file of a fix filename template ( bat

%RANDOM%.tmp in your case);
:uniqGetByMask : create a file of a variable filename template. Note quadrupled percent signs of %random% reference in a procedure call: prefix%%%%random%%%%suffix.ext . Also note advanced usage: CALL ing internal commands in call set «_uniqueFileName=%

2″ inside the procedure.

The code could be as follows:

Output:

I suggest you one of two methods. The «technical approach» is to use JScript’s FileSystemObject.GetTempName method. JScript is a programming language that comes pre-installed in all Windows versions from XP on, and its use in Batch via a «Batch-JScript» hybrid script is very simple:

However, the simplest approach is to store a number in a data file and every time that you want a new name, get the number, increment it and store it back in the same file. This will work for «just» 2147483647 times!

Firstly, using a separate folder will significantly reduce the chances of other programs intruding. So lets store the temp file in a private folder that’s really long and specific to prevent any name competition.

When generating the name, you could always use %random% and try generating a name which does not exist, however the more times this operation is use, the more ineffective it becomes. If you plan to use this process 10’s of thousands of times as the random function is limited to 32000 (approximately) your program will spend forever generating random attempts.

The next best approach is to start a counter at one and increase it till you have an unused name. That way you can guarantee your program will eventually find a name in a reasonable amount of time, however again your files will pile up (which is never a good experience)

What some people do (and I would recommend for your situation) is combine these to processes to effectively cut the fat in selecting a name, while using a reliable method (the best of both worlds):

Как создать пакетный файл BAT для выполнения в командной строке CMD

Batch (.bat) файл — это инструмент, который сэкономит вам не один десяток часов рабочего времени. Узнайте сейчас как использовать пакетный файл на практике.

Пакетный (BAT, batch) файл представляет собой инструмент, с которым сталкивался практически каждый пользователь Windows. Документ помогает выполнить ряд действий буквально парой кликов, а их список ограничивается лишь силой воображения и кодовым функционалом. Давайте разберем инструмент подробнее.

Что такое BAT файл?

Вы, должно быть, уже в курсе о существовании такой утилиты как “Командная строка” Windows, или CMD. Она работает путем ввода команд в качестве входных данных и обрабатывает их, проводя нужные операции с компьютером. Тем не менее, несмотря на всю полезность инструмента, командная строка устраивает далеко не всех. Сложность утилиты и высокий порог вхождения делают ее “последним средством спасения Windows”.

Чтобы упростить процесс работы и сделать его более быстрым, Microsoft ввели посредника между “человеком” и “машиной”. Этим посредником стал пакетный файл (batch file). Запущенный на компьютере документ автоматически выполняет команды в CMD, ограждая пользователя от собственноручной работы. Процесс автоматизации назван пакетным сценарием (batch script).

Доступные форматы BAT файла:

Вне зависимости от того какой формат выбран при создании документа, функции от этого не изменятся.

В чем польза BAT файла?

Автоматизация. Если раньше вам приходилось долго и нудно “вбивать” сложные коды в окно командной строки, пришло время расслабиться! BAT файл экономит время пользователя не только при работе с CMD, но и при взаимодействии с другими системами ПК. Например, вы можете запланировать выключение компьютера через определенный промежуток времени. Этот способ применения пакетного файла хорошо подойдет геймерам, ставящим установку игру на ночь. Запланируйте отключение системы к моменту завершения установки и не опасайтесь за перерасход электроэнергии.

Если же вы разработчик программного обеспечения, обратите внимание на возможность автоматизации при установке вашего приложения. Таким образом повысится не только удобство для конечного пользователя, но популярность вашего софта.

При создании BAT файла используется петля (for), условный оператор (if) и оператор управления (goto). Документ запускается либо с помощью командной строки, либо с помощью другого пакетного файла при использовании команды CALL.

Режимы BAT файла

Несмотря на то, что пакетный файл по умолчанию выполняет работу автоматически, вы можете настроить его так, что при выполнении конкретной операции он будет запрашивать подтверждение. Например, при вводе команды на отключение службы Windows, BAT файл спросит вас, уверены ли вы в своем решении. Этот режим называется интерактивным (interactive).

Другой режим называется пакетным (batch mode). Он работает в классическом стиле и самостоятельно выполняет запрограммированные функции.

Режимы пакетного файла:

  • Интерактивный.
    Полуавтоматический режим. Программа может запрашивать подтверждение операций.
  • Пакетный.
    Полная автоматизация работы.

Используйте разные режимы в зависимости от ситуации.

Как запустить BAT файл в Windows 10?

Основной способ запуска пакетного файла — двойной щелчок по его иконке. Тем не менее, вы можете его и открыть и другим методом — с помощью командной строки.

Чтобы открыть BAT файл с помощью командной строки, выполните следующее:

  • Откройте директорию в которой лежит пакетный файл.
  • Определите название файла.
  • Откройте командную строку.
  • Введите название документа с его расширением.
    Например: HelloWorld.bat

Способ запуска через командную строку приобретает ценность с ростом количества пакетных файлов. Если вы помните название и расширение нужного документа, вы откроете его даже когда забыли точную директорию.

Как создать BAT файл?

Эта тема разбита на 2 раздела, каждый из которых — ключевой при создании пакетного документа. Не зная основ и команд, нужных для формирования структуры, автоматизировать процесс работы невозможно.

Основы создания BAT файлов

Вы не сможете создать пакетный файл без изучения базовых команд. Каким бы он не был полезным и не помогал автоматизировать работу на ПК, непонимание основ станет серьезным препятствием. В этом разделе мы рассмотрим 5 базовых команд, которые вас в курс дела.

  • title
    Используется для создания заголовка. Отображается в верхней части окна командной строки.
  • echo
    Режим вывода команд на экран. При включении, командная строка выведет на экран сообщение о совершенном действии. При отключении, соответственно, сообщения пропадут. Обратите внимание, что вам придется контролировать статус echo . Если команда активирована на строке 2 и вы решили отключить ее на строке 22, 20 промежуточных строк будут содержать включенный режим вывода команд.
  • pause
    Используется для остановки процесса.
  • exit
    Позволяет закрыть командную строку.
  • cls
    Используется для очистки окна командной строки.
  • ::
    Позволяет добавить комментарий к действию пакетного файла. Команда является пассивной и не влияет на общую работу документа.

Представленные выше команды — базовые и присутствуют во всех версиях Windows. Дополнительные команды появляются при установке соответствующего программного обеспечения. Например, если вы хотите автоматизировать задачи браузера Google Chrome, введите соответствующий код под названием chrome .

Используя эту информацию как фундамент для создания BAT файлов, вы можете автоматизировать любой процесс на ПК.

Руководство по созданию BAT файла

В этом разделе мы рассмотрим алгоритм создания пакетного файла, который подойдет для Windows 10, Windows 8.1, Windows 7 и даже для Windows XP.

1. Откройте Блокнот . При желании, воспользуйтесь альтернативой стандартному приложению — Notepad++ .

2. С помощью команду echo off временно отключите комментарии, чтобы не засорять окно.

3. Введите заголовок title My First Bat File .

4. Добавьте комментарий This comment will not appear in the command prompt.
Следует отметить, что по умолчанию в командной строке отображается только английский язык. Тем не менее, комментарий может быть на любом другом. Он не будет отображаться в CMD и останется только в блокноте. Комментарий — ваша личная заметка, чтобы не потеряться в коде.

5. Введите команду echo Test file executed .

6. Далее введите I am too lazy to write commands by myself .

7. И, наконец, команда paust , чтобы обозначить завершение процесса.

8. Сохраните документ, изменив формат с .txt на .bat .


Empty files are those with a file size of zero bytes and no data stored in them. You can make an empty text file, word document, or whatever you want.

With the «touch» command in Linux, we can easily create an empty file. In Windows OS, there is no direct equivalent command for touch. But don’t worry, you can accomplish the same thing using a variety of methods in Windows, which I will go over in detail.

Table of Contents

  • 1 Using Echo Command in Command Prompt or Batch File
  • 2 Using Copy Command in Command Prompt or Batch File
  • 3 Using winit in Command Prompt or Batch File
  • 4 Using REM in Command Prompt or Batch File
  • 5 Using Powershell 
  • 6 Using Type Operator in Command Prompt or Batch File
  • 7 Using fsutil Command in Command Prompt or Batch File
  • 8  Using Colon Operator in Command Prompt / Batch File

In general, we like to create a dummy file just for testing our application and then add the information as needed later. You can create an Empty File with the GUI, Command Prompt, or Powershell.

1 Using Echo Command in Command Prompt or Batch File

The echo command in Windows is used to display a string provided by the user. We can create an empty file using Echo and let’s look at the syntax at first.

Here you have to understand follow points:

— No need for administrative privileges.
— In this method, if the file already exists then also it will overwrite the file and create the new one.

1a) Method 1

Syntax:

echo -n "" > filenamewithpath 

Where «filenamewithpath» indicates you create a filename with a path mentioned in it.

Example:

echo -n "" > D:empty.txt

Inside D drive, I’m making an empty.txt file.

> is a redirection operator, and is used to send whatever is ever-present on the left to the right. Here echo is holding empty string «» and an empty string is written to the file empty.txt.This empty string will have 0 sizes.

You can replace D:empty.txt with whatever you like.

Note that if you are going to write in C drive (or any drive where windows is installed) then you may get access denied.

1b) Method2

Combining echo on/off with & operator

echo off > D:empty.txt & echo on

empty-text-file

fig. Empty Text File using Echo Command

1c) Method 3

 echo. 2>"D:empty.txt"

2 Using Copy Command in Command Prompt or Batch File

The Copy command in Windows is typically used to copy one or more files from one location to another. They can be used to create files, empty files, and so on.

Notes:

  • No need for administrative privileges.
  • In this method, if the file already exists then also it will overwrite the file and create the new one.

Example:

COPY NUL  "D:/empty.txt"  > NUL 

If the file does not exist, the copy will create a new one; if it does exist, it will overwrite the previous one.

In this case, we’re copying NUL to the empty.txt file, and the «> NUL» indicates that it will not display any success or failure messages like «1 file(s) copied.» or «Overwrite asdddff.txt? (Yes/No/All):»

3 Using winit in Command Prompt or Batch File

wininit is a Microsoft Windows operating system software component. Using winit.exe, we can create an empty file.

Notes:

  • No need for administrative privileges.
  • In this method, if the file already exists then also it will overwrite the file and create the new one.

Example:

wininit >D:empty.txt

4 Using REM in Command Prompt or Batch File

REM is an abbreviation for Remark. It supports the inclusion of comments within batch files. REM can be used to create the empty file shown below.

Notes:

  • No need for administrative privileges.
  • In this method, if the file already exists then also it will overwrite the file and create the new one.

Example:

REM. >D:empty.txt

5 Using Powershell 

Microsoft Powershell is a set of task automation and configuration management tools. We can use this tool to create an empty file.Simply launch PowerShell and enter the following:

Example:

New-Item D:empty.txt

Just replace empty.txt with whatever you want. 

6 Using Type Operator in Command Prompt or Batch File

type is an in-built command that displays the contents of a text file.

Notes:

  • No need for administrative privileges.
  • In this method, if the file already exists then also it will overwrite the file and create the new one.

Example:

type NUL > D:empty.txt

7 Using fsutil Command in Command Prompt or Batch File

Notes:

  • Need for administrative privileges.
  • In this method, if the file already exists then it doesn’t overwrite the file and will prompt you with an error like «Error:  The file exists.» and if you include «< nul» in the command then it will not prompt a message.

Example:

fsutil file createnew D:empty1.txt 0 > nul

8  Using Colon Operator in Command Prompt / Batch File

Example:

: > D:empty.txt

FAQ:

How to create read-only empty files in Windows?

We can easily create read-only and empty files in Windows by combining two texts one creates an empty text file and then set read-only permission to the file.»type Nul > abc.txt» creates an empty file and «attrib +r abc.txt» creates read-only permission for the same file. Here, attrib is used to set and remove file attributes like hidden(h), read-only(r), system(s) and archive(a).

 type Nul > abc.txt & attrib +r abc.txt

If you want to remove read-only from this you can use the «-r» parameter instead of «+r» 

 How to create a hidden empty file in Windows?

For this we use «+h» parameter as shown below.

type Nul > abc.txt & attrib +h abc.txt

How to create multiple empty files in Windows?

For creating multiple we can use for loop to generate the empty file. Here we are creating 10 empty files in the current location. The filename will be respectively:myemptyfile-1.txt,myemptyfile-2.txt,myemptyfile-3.txt and soon up to myemptyfile-10.txt

for /l %a in (1 1 10) do type nul > "myemptyfile-%a.txt"

creating-multiple-empty-files

fig. Create multiple empty file

Can we create Empty doc, xlsx files in Windows?

Yes, you can create empty docs, and xlsx files using any of the above methods. You can simply try like this:

type NUL > D:emptyDocsFile.docx

empty-docs-file.

fig. Creating empty docs file 

Conclusion:

With the aforementioned methods, we can successfully create empty files such as txt, Docx, xlsx, or any text file.

on February 6, 2012

In Linux, we can create an empty file using ‘touch‘ command. There’s no equivalent command for touch in Windows OS. However, we can still create zero byte files using  the command fsutil.

The syntax of fsutil command for creating a file is:

fsutil file createnew filename  requiredSize

Below is the command you can run to create a empty text file.

fsutil file createnew filename 0

Example:

C:>fsutil file createnew emptyfile.txt 0
File C:emptyfile.txt is created

C:>dir emptyfile.txt
02/06/2012  10:50 PM                 0 emptyfile.txt
 C:>

The above command can be run from a batch file also. It works on all Windows editions: XP, Server 2003, Vista, Windows 7, Server 2008.

fsutil‘ command should be run from elevated administrator command prompt. Otherwise, you would get the below error message.

c:>fsutil file createnew emptyfile.txt 0
The FSUTIL utility requires that you have administrative privileges.

Using echo command

In Linux, we can use echo command also to create empty text files. This command is available in Windows also.
But using ‘echo’ we can’t create empty files. See below.

c:> echo > newfile.txt
c:>
c:>dir newfile.txt
02/06/2012  10:47 PM                13 newfile.txt
c:>

As you can see, it has created a file of size 13 bytes.

Related Posts:

  • Create large file from command line
  • FSUTIL command

Понравилась статья? Поделить с друзьями:
  • Windows command kill process command line
  • Windows com stopcode что это такое
  • Windows com stopcode что это значит
  • Windows com stopcode что делать код остановки
  • Windows com stopcode что делать bad system config info