Командная строка windows touch

Windows эквивалент командной строки «touch»?

Что вы используете, если хотите обновить поле, модифицированное датой файла в Windows?

  1. команды , доступные через C ++, .NET, C # или что-то родное для Windows (желательно Vista)
  2. инструменты /приложения желательно бесплатно и, если возможно, с открытым исходным кодом, а также

Изменить: уже существует страница для приложений, как указано CheapScotsman здесь .

Если кто-то знает, как я могу это сделать с помощью C ++, C #, WSH или что-то подобное, хорошо и хорошо, иначе я бы подумал, что все остальное связано с связанным вопросом.

30 ответов

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

(где filename.ext — имя вашего файла). +,, — это специальный флаг для copy , говорящий просто обновить дату /время в файле :

* Изменение времени и даты файла

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

В запятых указывается пропуск параметра Destination.

Изменить на основе комментариев Луми и Джастина: поместите это в пакетный файл, например. touch.cmd

Это работает, даже если файл отсутствует в текущем каталоге (протестирован в Windows 7).

Я использовал и рекомендую unxutils , которые являются родными портами Win32 многих распространенных утилит Unix. Существует команда touch .

Если вы хотите изменить последнюю измененную дату файла (это было мое дело):

  • Создает file , если он не существует.
  • Оставляет только содержимое файла.
  • Просто использует встроенные модули cmd .
  • Обновлены те последний доступ и создание .

UPDATE

Г! Это не работает с файлами только для чтения, тогда как touch делает. Я предлагаю:

Вот объяснение Технетом таинственных «+» и запятых:

copy /b Источник + ,,

Эти запятые указывают на отсутствие Параметр назначения.

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

Если вам нравится его кодирование самостоятельно, .NET предлагает File.SetLastAccessTime , File.SetCreationTime и File.SetLastWriteTime .

здесь рекурсивная версия с использованием powershell . это изменит последнее измененное время для всех файлов и подкаталогов, а также файлы в подкаталогах этого каталога

Проект GnuWin32 имеет порты Windows из версий Gnu утилит командной строки Unix.

Он поставляется в виде нескольких отдельных пакетов, и вы можете установить только нужные вам команды без каких-либо других зависимостей. Для touch вам понадобится пакет CoreUtils .

Я попробовал это, чтобы создать пустой файл в моем пакетном скрипте. Вы можете использовать это:

cygwin поставляется с touch . Я знаю, что вы упомянули, что вы не хотите устанавливать целую фреймворк, но cygwin довольно легкий и может быть вызван из окна команд dos без включения всей командной строки, подобной unix.

Вы также можете контролировать, какие инструменты устанавливать, поэтому вы можете просто установить файл touch.exe и оставить остальную часть фреймворка.

Вот простой regfile, который я написал в добавить правую кнопку мыши » touch «в проводнике Windows . Слишком легко его создать, так как он просто вызывает:

Я использовал его раньше, и он работает хорошо — без установки, без DLL и т. д.

  • Не нужно устанавливать.
  • Если вы хотите, вы можете даже изменить источник.

Вы также можете установить Cygwin , который дает вам Touch, а также множество других команд * NIX.

Существуют порты Windows многих утилит Unix. Посмотрите unxutils или Проекты GnuWin32 .

Из аналогичного вопроса о переполнении стека.

Для обновления временных меток (игнорируя другие функции touch ), я бы пошел с:

Funuction Software Touch — бесплатная утилита «touch», которая позволяет вам изменить время /дату и /или метки атрибутов на один или несколько файлов. В дополнение, FS Touch может добавить /вычесть указанное количество секунд из существующее время файла. Вы можете указать, какие файлы и /или подкаталоги для изменения через «сложные маски файлов». Программа может быть запускаться из интерактивной или командной строки. Новое для версии 7.2 — это командной строки, чтобы изменить измененную временную метку файла +/- заданное количество секунд.

FS Touch работает в Windows XP, Vista, Windows 7 и & Windows 8.

Если вы используете git для одного или нескольких проектов, на основе git-bash на основе mingw для Windows есть команда touch . Я хочу поблагодарить @ greg-hewgill за то, что указал на то, что для Windows существуют утилиты nix, потому что именно это заставило меня попытаться прикоснуться к git-bash.

Читайте также:  Иконки с старых windows

Этот контент можно сохранить в файл reg. Это добавит контекстное меню правой кнопки мыши для всех файлов с возможностью «Touch File» (проверено на Windows 7). Скопируйте все следующие строки в файл reg. Запустите файл и подтвердите вопрос. Щелкните правой кнопкой мыши на любом файле (или нескольких файлах). Теперь доступна опция «Touch File».

в PowerShell попробуйте:

NI является псевдонимом New- Элемент .

Сохраните следующее как touch.bat в папке% windir% \ system32 или добавьте папке, в которой она сохраняется в вашей переменной среды PATH:

Я нашел быстрый способ сделать это, если у вас установлен vim (не большой для больших файлов, откроет весь файл и закроет его . )

«+» устанавливает аргумент для запуска следующих команд. «WQ!» это «написать, выйти, заставить». Это откроет файл, сохранит его, а затем закроет его сразу же.

Файл fsutil createnew new.txt 0

Пять альтернатив, упомянутых выше, плюс три других, не упомянутых здесь, можно найти в SuperUser: » Windows Recursive Touch Command »

Это немного не связано с исходным вопросом, но я считаю это очень полезным для Windows из-за GUI.

Я использую утилиту TouchPro, которая предоставляет графический интерфейс пользователя (встраивается в оболочку проводника):

Люди Unix исправили общую проблему обновления даты файла любого файла с помощью команды touch . Однако для Windows иногда возможен более простой метод для особых случаев.

Мне нужно обновить временную метку ярлыка приложения в Windows 8.1, чтобы сделать видимыми изменения цвета фона панели приложений, см. этот вопрос SO . Вместо того, чтобы использовать один из умных инструментов выше, мне легче редактировать поле комментария ярлыка. Большинство людей оставляют это пустое, но, конечно, полезный комментарий быстро задуман. И если комментарий существует, добавление или удаление последнего периода никогда не наносит вреда.

Я ценю, что это старый вопрос, я просто обнаружил, что касаюсь своей системы Windows 10. Я загрузил и установил Git из здесь (я думаю), и это выглядит как прикосновение и различные другие Утилиты находятся в папке bin.

Ну, если вы действительно хотите иметь команду touch , вы можете поместить ее в пакетный файл с именем touch.bat и вставьте его в C:\Windows :

Мне нужна функция «touch» для клонирования /дублирования дат файла из другого файла, изначально и может использоваться из пакетного файла.

Итак, видеофайл для «перетаскивания» в пакетный файл, запускается FFMPEG, затем «Дата создания» и «Дата изменения» из входного файла копируется в выходной файл.

Это казалось простым вначале, пока вы не обнаружите, что пакетные файлы ужасны при работе с именами файлов Unicode, встроенный PowerShell испорчен символами имен файлов, а двойной выход из них — это кошмар.

Мое решение сделало «touch» частью отдельный сценарий PowerShell, который я назвал «CLONE-FILE-DATE.ps1», и он содержит:

Тогда вот пример использования в моем командном файле CONVERT.BAT:

Я думаю, что PowerShell читаем, поэтому просто объясните, что говорит пакет:

dp0 — это текущий каталог командного файла.

1 — это путь к файлу, опущенному на пакет без кавычек.

CHCP 65001> nul устанавливает символы в UTF-8 и проглатывает вывод.

-ExecutionPolicy ByPass позволяет запускать PowerShell без необходимости изменения глобальной политики, которая существует для предотвращения случайного запуска скриптов.

Create an empty file on the commandline in windows (like the linux touch command)

On a windows machine I get this error

‘touch’ is not recognized as an internal or external command, operable program or batch file.

I was following these instructions which seem to be linux specific, but on a standard windows commandline it does not work like this:

Is there a windows equivalent of the ‘touch’ command from the linux / mac os / unix world ? Do I need to create these files by hand (and modify them to change the timestamp) in order to implement this sort of command? I am working with node and that doesn’t seem very . node-ish.

20 Answers 20

An easy way to replace the touch command on a windows command line like cmd would be:

This will create 0 bytes in the your_file.txt file.

This would also be a good solution to use in windows batch files.

Another way of doing it is by using the echo command:

echo. — will create a file with one empty line in it.

If you need to preserve the content of the file use >> instead of >

You can also use call command.

Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call.

Windows does not natively include a touch command.

Читайте также:  Как через консоль активировать windows

You can use any of the available public versions or you can use your own version. Save this code as touch.cmd and place it somewhere in your path

It will iterate over it argument list, and for each element if it exists, update the file timestamp, else, create it.

You can use this command: ECHO >> filename.txt

it will create a file with the given extension in the current folder.

UPDATE:

for an empty file use: copy NUL filename.txt

The answer is wrong, it only works when the file does not exist. If the file exists, using the first does nothing, the second adds a line at the end of the file.

The correct answer is:

On windows Power Shell, you can use the following command:

Note: New-Item can be replaced with its alias ni

I’m surprised how many answers here are just wrong. Echoing nothing into a file will fill the file with something like ECHO is ON , and trying to echo $nul into a file will literally place $nul into the file. Additionally for PowerShell, echoing $null into a file won’t actually make a 0kb file, but something encoded as UCS-2 LE BOM , which can get messy if you need to make sure your files don’t have a byte-order mark.

After testing all the answers here and referencing some similar ones, I can guarantee these will work per console shell. Just change FileName.FileExtension to the full or relative-path of the file you want to touch ; thanks to Keith Russell for the COPY NUL FILE.EXT update:

CMD w/Timestamp Updates

copy NUL FileName.FileExtension

This will create a new file named whatever you placed instead of FileName.FileExtension with a size of 0 bytes. If the file already exists it will basically copy itself in-place to update the timestamp. I’d say this is more of a workaround than 1:1 functionality with touch but I don’t know of any built-in tools for CMD that can accomplish updating a file’s timestamp without changing any of its other content.

CMD w/out Timestamp Updates

if not exist FileName.FileExtension copy NUL FileName.FileExtension

Powershell w/Timestamp Updates

if (!(Test-Path FileName.FileExtension -PathType Leaf)) else

Yes, it will work in-console as a one-liner; no requirement to place it in a PowerShell script file.

Windows equivalent of the Linux command ‘touch’?

What do you use when you want to update the date-modified field of a file on Windows?

  1. commands accessible via C++, .NET, C#, or something native to Windows (Vista preferably)
  2. tools/applications preferably free, and if possible open source as well

Edit: there is already a page for applications as pointed out by CheapScotsman here.

If anyone knows how I can do this via C++, C#, WSH or something similar, well and good, else I would think everything else is covered in the linked question.

31 Answers 31

If you want to touch the date stamp of a file using windows, use the following command at the command prompt:

(where filename.ext is your file’s name). The +,, is a special flag to copy telling it to simply update the date/time on the file:

* Changing the time and date of a file

If you want to assign the current time and date to a file without modifying the file, use the following syntax:

The commas indicate the omission of the Destination parameter.

Edit based on comments by Lumi and Justin: put this in a batch file, eg. touch.cmd

This works even if the file is not in the current directory (tested on Windows 7).

I’ve used and recommend unxutils which are native Win32 ports of lots of common Unix utilities. There is a touch command in there.

If all you want is to change the file’s last modified date (which was my case):

  • Creates file if it does not exist.
  • Leaves file contents alone.
  • Just uses cmd built-ins.
  • Both last-access and creation times updated.

UPDATE

Gah! This doesn’t work on read-only files, whereas touch does. I suggest:

Here is Technet’s explanation of the mysterious ‘+’ and commas:

The commas indicate the omission of the Destination parameter.

The copy command supports merging multiple files into a single destination file. Since a blank destination cannot be specified using a space character at the command prompt, two commas can be used to denote that.

If you feel like coding it yourself, .NET offers the File.SetLastAccessTime , File.SetCreationTime and File.SetLastWriteTime methods.

here is a recursive version using powershell. this will change the last modified time for all files and subdirectories, and files within this directory’s subdirectories

Читайте также:  Как поменять uuid диска linux

I tried this to create an empty file in my batch script. You can use this:

The GnuWin32 project has Windows ports of the Gnu versions of the Unix command line utilities.

It comes as a number of separate packages and you can install just the commands you need with no other dependencies. For touch you would need the CoreUtils package.

cygwin comes with touch . I know you mentioned that you don’t want to install a whole framework, but cygwin is quite lightweight, and can be called from dos command window without the whole unix-like command line turned on.

You can also control what tools to install, so you could simply install the touch.exe file, and leave the rest of the framework.

Here’s a simple regfile I wrote to add right-click «touch» in Windows explorer. It’d be easy to script it, too, since it just calls:

I’ve used it before and it works well — no installation, no DLLs, etc

Try this one from CodeProject.

  • No need to install.
  • If you want, you can even modify the source.

You could also install Cygwin which gives you Touch as well as a plethora of other *NIX commands.

This content can be saved to a reg file. This will add a right click context menu for all files with the «Touch File» ability (tested on Windows 7). Copy all the following lines to reg file. Run the file and approve the question. Right click on any file (or multiple files) — «Touch File» option is now available.

There are Windows ports of many Unix utilities. Have a look at unxutils or GnuWin32 projects.

From a similar question on Stack Overflow.

For updating timestamps (ignoring the other functionality of touch ), I’d go with:

from the website:

Funduc Software Touch is a free ‘touch’ utility that allows you to change the time/date &/or attribute stamps on one or more files. In addition, FS Touch can add/subtract a specified number of seconds from the existing file time. You can specify which file(s) and/or subdirectories to change via ‘complex file masks’. The program can be run from interactively or the command line. New to version 7.2 is a command line switch to change file modified time stamp +/- the specified number of seconds.

FS Touch runs on Windows XP, Vista, Windows 7, & Windows 8.

If you are using git for one or more projects, the mingw based git-bash for Windows has the touch command. I want to thank @greg-hewgill for pointing out to me that ‘nix utilities exist for windows, because it was that which put me on the idea to try touch in git-bash.

in PowerShell try:

NI is an alias of the New-Item cmdlet.

Save the following as touch.bat in your %windir%\system32 folder or add the folder in which it is saved to your PATH environment variable:

I found a quick way to do it if you have vim installed (not great for big files, will open entire file then close it. )

The «+» sets argument to run the following commands. «wq!» is «write, quit, force». This will open file, do a save, then close it immediately afterward.

I wanted the ‘touch’ feature of cloning / duplicating the file dates from another file, natively, and be usable from a batch file.

So ‘drag and drop’ video file on to batch file, FFMPEG runs, then ‘Date Created’ and ‘Date Modified’ from the input file gets copied to the output file.

This seemed simple at first until you find batch files are terrible at handling unicode file names, in-line PowerShell messes up with file name symbols, and double escaping them is a nightmare.

My solution was make the ‘touch’ part a seperate PowerShell script which I called ‘CLONE-FILE-DATE.ps1’ and it contains:

Then here is example usage within my ‘CONVERT.BAT’ batch file:

I think the PowerShell is readable, so will just explain the batch speak:

dp0 is the current directory of the batch file.

1 is the path of the file dropped onto the batch without quotes.

CHCP 65001 > nul sets characters to UTF-8 and swallows the output.

-ExecutionPolicy ByPass allows you to run PowerShell without needing to modify the global policy, which is there to prevent people accidentally running scripts.

Оцените статью