- TOUCH (Windows 2000 Resource Kit)
- An alternative Touch using the COPY command.
- Windows эквивалент командной строки «touch»?
- 30 ответов
- Windows recursive touch command
- 9 Answers 9
- Create an empty file on the commandline in windows (like the linux touch command)
- 20 Answers 20
- CMD w/Timestamp Updates
- CMD w/out Timestamp Updates
- Powershell w/Timestamp Updates
TOUCH (Windows 2000 Resource Kit)
Change file timestamps
This is a POSIX utility.
Use the optional argument /t to specify a date other than the current time.
( four-digit years, two-digit months, days, hours, minutes, seconds)
An alternative Touch using the COPY command.
As first documented in the ancient (MSDOS) KB article Q69581 the COPY /b command can be used to touch the date/time of a file:
COPY /B Source.txt+,,Source.txt
This takes a source file, adds nothing (represented by the commas) and copies it to the same file as a destination. If you are working in a single folder, the second filename can be omitted as it will default to writing the same filename.
or as a batch file:
@Echo Off
COPY /B %1+,, %1
There are a few caveats with this technique:
It fails for read-only or hidden files.
It may reset file permissions back to the default for the folder.
In some versions of Windows, if the file is 0 bytes long it will be deleted!
If the file is a binary file with trailing null characters (0x00), they will be deleted, corrupting the file.
It is no longer a documented option in current versions of Windows.
A better alternative is PowerShell, you can call a one-liner with powershell.exe
#And smiles you’ll give and tears you’ll cry
And all you touch and all you see
Is all your life will ever be#
Pink Floyd (Breathe)
Q299648 — Date and Time Stamps for Files and Folders (FAT vs NTFS)
COPY — Copy one or more files to another location.
Equivalent PowerShell Script: touch — Change file timestamps.
Equivalent bash command (Linux): touch — Change file timestamps.
Windows эквивалент командной строки «touch»?
Что вы используете, если хотите обновить поле, модифицированное датой файла в Windows?
- команды , доступные через C ++, .NET, C # или что-то родное для Windows (желательно Vista)
- инструменты /приложения желательно бесплатно и, если возможно, с открытым исходным кодом, а также
Изменить: уже существует страница для приложений, как указано 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.
Этот контент можно сохранить в файл 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 без необходимости изменения глобальной политики, которая существует для предотвращения случайного запуска скриптов.
Windows recursive touch command
In Windows 7, how can I recursively touch all files in a directory (including subdirectories) in order to update the date/time stamp?
Does Windows 7 have a mechanism to accomplish this?
9 Answers 9
There are several possibilities:
Use a port of a Unix touch command and simply combine find and touch in the Unix way. There are several choices. Oft-mentioned are GNUWin32, cygwin, and unxutils. Less well known, but in some ways better, are the tools in the SFUA utility toolkit, which run in the Subsystem for UNIX-based Applications that comes right there in the box with Windows 7 Ultimate edition and Windows Server 2008 R2. (For Windows XP, one can download and install Services for UNIX version 3.5.) This toolkit has a large number of command-line TUI tools, from mv and du , through the Korn and C shells, to perl and awk . It comes in both x86-64 and IA64 flavours as well as x86-32. The programs run in Windows’ native proper POSIX environment, rather than with emulator DLLs (such as cygwin1.dll ) layering things over Win32. And yes, the toolkit has touch and find , as well as some 300 others.
All of these toolkits have the well-known disadvantage of running a separate process for every file to be touched, of course. That’s not a problem with the following alternatives.
Use one of the many native Win32 touch commands that people have written and published. Many of them support options to perform recursion, without the necessity for a Unix find to wrap around them. (They are, after all, targeting a userbase that is looking for a touch command because it doesn’t have a whole load of ported Unix commands.) One such is Stéphane Duguay’s touch which as you can see has a —recursive option.
Get clever with the arcane mysteries of CMD. As mentioned in the other answer, COPY /B myfile+,, will update a file’s last modification datestamp, using the little-known «plus» syntax of the COPY command (more on which can be found here, incidentally). This of course can be combined with FOR /R to perform the operation recursively, as hinted at in another answer here.
Use a replacement command interpreter and be less clever and more straightforward than CMD. JP Software’s TCC/LE is one such. It adds an /S option to its COPY command, meaning that one could use COPY /S with the «plus» syntax to eliminate the need for a FOR wrapper. But that’s really still making life unnecessarily difficult for oneself, considering that TCC/LE has a built in TOUCH command that directly supports an /S option.
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.
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))
Yes, it will work in-console as a one-liner; no requirement to place it in a PowerShell script file.