Touch linux команда аналог в windows

The equivalent of the Linux `touch` command in Windows command-line prompt (CMD) and Windows PowerShell. Create a new file or change a file timestamps.

The touch command in Linux is used to change a file’s “Access“, “Modify” and “Change” timestamps to the current time and date, but if the file doesn’t exist, the touch command creates it.

If you simply want to create an empty file from the command-line prompt (CMD) or a Windows PowerShell – the type and copy commands can be considered as a Windows touch command equivalent.

The file timestamps in Windows can be changed using the built-in PowerShell commands.

Cool Tip: Windows cat command equivalent in CMD and PowerShell! Read more →

To create a new file, as a Windows touch equivalent, you can use one of these commands:

C:> type nul >> "file.txt"
- or -
C:> copy nul "file.txt"

To change a file timestamps to the current time and date, execute the following commands from the PowerShell:

PS C:> (Get-Item "file.txt").CreationTime=$(Get-Date -format o)
PS C:> (Get-Item "file.txt").LastWriteTime=$(Get-Date -format o)
PS C:> (Get-Item "file.txt").LastAccessTime=$(Get-Date -format o)

Cool Tip: Windows grep command equivalent in CMD and PowerShell! Read more →

To set the specific timestamps, execute:

PS C:> (Get-Item "file.txt").CreationTime=("01 March 2020 09:00:00")
PS C:> (Get-Item "file.txt").LastWriteTime=("20 April 2020 17:00:00")
PS C:> (Get-Item "file.txt").LastAccessTime=("20 April 2020 17:00:00")

The timestamps can be displayed using the following command:

PS C:> Get-Item file.txt | Format-List CreationTime, LastAccessTime, LastWriteTime

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:

param
(
  [Parameter(Mandatory=$true)][string]$SourcePath,
  [Parameter(Mandatory=$true)][string]$TargetPath
)

(GI -LiteralPath $TargetPath).CreationTime  = (GI -LiteralPath $SourcePath).CreationTime
(GI -LiteralPath $TargetPath).LastWriteTime = (GI -LiteralPath $SourcePath).LastWriteTime

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

%~dp0ffmpeg -i "%~1" ACTION "%~1-output.mp4"

CHCP 65001 > nul && PowerShell -ExecutionPolicy ByPass -File "%~dp0CLONE-FILE-DATE.PS1" "%~1" "%~1-output.mp4"

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.

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

type nul > your_file.txt

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.> your_file.txt

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


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

>   Creates a new file
>>  Preserves content of the file

Example

type nul >> your_file.txt

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.

Example:

call >> your_file.txt


or even if you don’t want make it hard you can Just install Windows Subsystem for Linux (WSL). Then, type.

wsl touch

or

wsl touch textfilenametoedit.txt

Quotes are not needed.

answered Jun 10, 2016 at 20:43

Vlad Bezden's user avatar

Vlad BezdenVlad Bezden

79.7k23 gold badges247 silver badges178 bronze badges

9

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

@echo off
    setlocal enableextensions disabledelayedexpansion

    (for %%a in (%*) do if exist "%%~a" (
        pushd "%%~dpa" && ( copy /b "%%~nxa"+,, & popd )
    ) else (
        type nul > "%%~fa"
    )) >nul 2>&1

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

answered May 3, 2015 at 20:27

MC ND's user avatar

1

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

answered Feb 23, 2016 at 21:42

Aaron Clark's user avatar

Aaron ClarkAaron Clark

7429 silver badges16 bronze badges

5

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

New-Item <filename.extension>

or

New-Item <filename.extension> -type file

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

answered Nov 5, 2018 at 7:05

Raghuveer's user avatar

RaghuveerRaghuveer

6877 silver badges18 bronze badges

5

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)) {New-Item FileName.FileExtension -Type file} else {(ls FileName.FileExtension ).LastWriteTime = Get-Date}

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

PowerShell w/out Timestamp Updates

if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file}

answered Nov 13, 2018 at 1:34

kayleeFrye_onDeck's user avatar

6

Use the following command on the your command line:

fsutil file createnew filename  requiredSize

The parameters info as followed:

fsutil — File system utility ( the executable you are running )

file — triggers a file action

createnew — the action to perform (create a new file)

filename — would be literally the name of the file

requiredSize — would allocate a file size in bytes in the created file

answered May 3, 2015 at 7:44

Ofer Haber's user avatar

Ofer HaberOfer Haber

6184 silver badges10 bronze badges

6

install npm on you machine

run the below command in you command prompt.

npm install touch-cli -g

now you will be able to use touch cmd.

answered Jan 26, 2021 at 3:59

maxspan's user avatar

maxspanmaxspan

12.9k14 gold badges72 silver badges100 bronze badges

2

You can replicate the functionality of touch with the following command:

$>>filename

What this does is attempts to execute a program called $, but if $ does not exist (or is not an executable that produces output) then no output is produced by it. It is essentially a hack on the functionality, however you will get the following error message:

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

If you don’t want the error message then you can do one of two things:

type nul >> filename

Or:

$>>filename 2>nul

The type command tries to display the contents of nul, which does nothing but returns an EOF (end of file) when read.

2>nul sends error-output (output 2) to nul (which ignores all input when written to). Obviously the second command (with 2>nul) is made redundant by the type command since it is quicker to type. But at least you now have the option and the knowledge.

answered Jul 1, 2017 at 9:40

Keldon Alleyne's user avatar

1

as mentioned

echo >> index.html

it can be any file, with any extension
then do

notepad index.html

this will open your file in the notepad editor

answered Jul 20, 2018 at 12:42

navarq's user avatar

navarqnavarq

9452 gold badges13 silver badges19 bronze badges

For a very simple version of touch which would be mostly used to create a 0 byte file in the current directory, an alternative would be creating a touch.bat file and either adding it to the %Path% or copying it to the C:WindowsSystem32 directory, like so:

touch.bat

@echo off
powershell New-Item %* -ItemType file

Creating a single file

C:UsersYourNameDesktop>touch a.txt

    Directory: C:UsersYourNameDesktop

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2020-10-14  10:28 PM              0 a.txt

Creating multiple files

C:UsersYourNameDesktop>touch "b.txt,c.txt"

    Directory: C:UsersYourNameDesktop

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2020-10-14  10:52 PM              0 b.txt
-a----        2020-10-14  10:52 PM              0 c.txt

Also

  • Works both with PowerShell and the Command Prompt.
  • Works with existing subdirectories.
  • Does not create a file if it already exists:
New-Item : The file 'C:UsersYourNameDesktopa.txt' already exists.
  • For multiple files, creates only the files that do not exist.
    • Accepts a comma-separated list of filenames without spaces or enclosed in quotes if spaces are necessary:
C:UsersYourNameDesktop>touch d.txt,e.txt,f.txt
C:UsersYourNameDesktop>touch "g.txt, 'name with spaces.txt'"

answered Oct 15, 2020 at 2:46

rbento's user avatar

rbentorbento

8,8003 gold badges59 silver badges58 bronze badges

You can also use copy con [filename] in a Windows command window (cmd.exe):

C:copy con yourfile.txt [enter]
C:CTRL + Z [enter] //hold CTRL key & press "Z" then press Enter key.
^Z
    1 Files Copied.

This will create a file named yourfile.txt in the local directory.

answered Sep 13, 2016 at 21:08

delliottg's user avatar

delliottgdelliottg

3,8702 gold badges39 silver badges49 bronze badges

I use cmder (a command line emulator)

It allows you to run all Linux commands inside a Windows machine.

It can be downloaded from https://cmder.net/

I really like it

answered Dec 14, 2019 at 7:08

user1880531's user avatar

1

From the Terminal of Visual Code Studio on Windows 10, this is what worked for me to create a new file:

type > hello.js
echo > orange.js
ni > peach.js

answered May 13, 2020 at 15:29

Enora's user avatar

EnoraEnora

1568 bronze badges

As Raghuveer points out in his/her answer, ni is the PowerShell alias for New-Item, so you can create files from a PowerShell prompt using ni instead of touch.

If you prefer to type touch instead of ni, you can set a touch alias to the PowerShell New-Item cmdlet.

Creating a touch command in Windows PowerShell:

From a PowerShell prompt, define the new alias.

Set-Alias -Name touch -Value New-Item

Now the touch command works almost the same as you are expecting. The only difference is that you’ll need to separate your list of files with commas.

touch index.html, app.js, style.css

Note that this only sets the alias for PowerShell. If PowerShell isn’t your thing, you can set up WSL or use bash for Windows.

Unfortunately the alias will be forgotten as soon as you end your PowerShell session. To make the alias permanent, you have to add it to your PowerShell user profile.

From a PowerShell prompt:

notepad $profile

Add your alias definition to your profile and save.

answered Sep 9, 2020 at 14:05

Jon Crowell's user avatar

Jon CrowellJon Crowell

21.3k14 gold badges88 silver badges110 bronze badges

If you have Cygwin installed in your PC, you can simply use the supplied executable for touch (also via windows command prompt):

C:cygwin64bintouch.exe <file_path>

answered Jun 12, 2019 at 8:37

Uri Ziv's user avatar

1

Assuming the file exists and you just need to update the timestamp.

type test.c > test.c.bkp && type test.c.bkp > test.c && del test.c.bkp

answered Dec 31, 2019 at 8:04

Anoop Kumar Narayanan's user avatar

Use rem. > file.txt (notice the dot attached to the command «rem»)

this creates an empty file

answered May 8, 2022 at 13:54

Joshua's user avatar

JoshuaJoshua

792 silver badges6 bronze badges

Shortest possible vanilla solution is :

.>myfile.txt

enter image description here

You will get an error , but file is created :

enter image description here

answered May 8, 2022 at 10:57

Royi Namir's user avatar

Royi NamirRoyi Namir

142k137 gold badges452 silver badges780 bronze badges

If you are using VS Code, there is a command line tool code to help you open a non-exist file in VS Code.

answered Mar 16, 2022 at 2:18

Wade's user avatar

WadeWade

111 silver badge1 bronze badge

There is something missing in all of the other answers. The Linux touch command has a -t option, which lets you set the last modified time to any arbitrary date and time, not just the current time.

This sets the modification date of filename.txt to 20 December 2012 at 30 minutes after midnight.

touch -t 201212210030 filename.txt

To get the equivalent in Windows, you need to be in PowerShell, it can’t be done in Cmd.

  • Change the creation date/timestamp of a file named filename.txt:
(Get-Item "D:Testfilename.txt").CreationTime=("21 December 2012 00:30:00")
  • Change the last write date/timestamp of a file named filename.txt:
(Get-Item "D:Testfilename.txt").LastWriteTime=("21 December 2012 00:30:00")
  • Change the last accessed date/timestamp of a file named filename.txt:
(Get-Item "D:Testfilename.txt").LastAccessTime=("21 December 2012 00:30:00")

answered Jul 7, 2022 at 9:56

Amedee Van Gasse's user avatar

Amedee Van GasseAmedee Van Gasse

7,0384 gold badges50 silver badges95 bronze badges

Using PowerShell, type: ni index.html or ni style.css or ni app.js

ni <filename>.<extension>

answered Jul 20, 2022 at 21:08

Kevin Kirsten Lucas's user avatar

1

If you have WSL with the appropriate distro like Ubuntu you can have the touch command in the CMD and not just the bash terminal. It works for me on Windows 10 & 11 Windows Terminal

answered Oct 24, 2022 at 16:00

Sebastian's user avatar

SebastianSebastian

3922 silver badges12 bronze badges

Easy, example with txt file

echo $null >> filename.txt

answered Feb 22, 2018 at 20:20

Thiago Maciel's user avatar

1

Yes you can use Node for Touch I just use that and its working all fine in windows Cmd or gitbash

enter image description here

Matheus Cuba's user avatar

Matheus Cuba

2,1281 gold badge21 silver badges30 bronze badges

answered Apr 11, 2018 at 20:09

Asad Iftikhar's user avatar

Asad IftikharAsad Iftikhar

531 gold badge3 silver badges10 bronze badges

1

Use type instead of touch

type YOUR_FILE_NAME

However, it is limited to just a single file

answered Dec 21, 2022 at 13:21

Tridib Roy Arjo's user avatar

2

It looks like your in PowerShell, which is slightly different than the Windows CMD-Prompt.


PowerShell Equivalent to the Linux Command $> touch


In PowerShell they the Command, a Cmdlet, and unlike BASH there is a specific Cmdlet for creating new files & directories (among other entities as well).


The PowerShell Cmdlet: $> New-Item


You can (for the most part) replace the BASH $> touch command with the PowerShell CmdLet $> New-item when creating files in a shell-environment.

Creating new items works a bit differently in PowerShell& than in Linux Shells (I am specifically referring to Bash in this answer).
For example, Windows PowerShell’s CmdLet $> New-item can create more than one type of item — for example, PowerShell create both directories, and files — therefore; in PowerShell, you need to specify the item type. To specify an item-type you will use the ItemType flag -ItemType <argument>. The pseudo-argument was a place holder I added in. Actual -ItemType arguments would be File &/or Directory.

EXAMPLE | New File:


Here is the Cmdlet format thats considered the standard for creating new files:

    New-Item -Path 'A:testingonetwothree.txt' -ItemType File


Creates the file, three.txt in the directory two, and the file’s full pathname would be, A:testingonetwothree.txt

EXAMPLE | New Directory:


The $> New-item CmdLet is specific for creating files & directories. This is somewhat unique, as the Linux Shell BASH implements the $> mkdir command, but it only makes directories, not files. BASH demonstrates that a SHELL doesn’t have to have a command thats specificly for file creation, however; that’s not to say that having a file-creation command doesn’t have any benifits. But, in Windows, you can, and you should, use the New-Item CmdLet for creating directories.

Here is how to create a directory when using PowerShell:

New-Item -Path 'Z:sum-directory' -ItemType Directory

This command creates a new directory named sum-directory. The directory is located in the drive-letter Z:, and the directory’s full pathname would be Z:sum-directory


FOR MORE INFORMATION ABOUT THIS TOPIC, PLEASE VISIT:

https://learn.microsoft.com/en-us/powershell/scripting/samples/working-with-files-and-folders?view=powershell-7.1#creating-files-and-folders

It looks like your in PowerShell, which is slightly different than the Windows CMD-Prompt.


PowerShell Equivalent to the Linux Command $> touch


In PowerShell they the Command, a Cmdlet, and unlike BASH there is a specific Cmdlet for creating new files & directories (among other entities as well).


The PowerShell Cmdlet: $> New-Item


You can (for the most part) replace the BASH $> touch command with the PowerShell CmdLet $> New-item when creating files in a shell-environment.

Creating new items works a bit differently in PowerShell& than in Linux Shells (I am specifically referring to Bash in this answer).
For example, Windows PowerShell’s CmdLet $> New-item can create more than one type of item — for example, PowerShell create both directories, and files — therefore; in PowerShell, you need to specify the item type. To specify an item-type you will use the ItemType flag -ItemType <argument>. The pseudo-argument was a place holder I added in. Actual -ItemType arguments would be File &/or Directory.

EXAMPLE | New File:


Here is the Cmdlet format thats considered the standard for creating new files:

    New-Item -Path 'A:testingonetwothree.txt' -ItemType File


Creates the file, three.txt in the directory two, and the file’s full pathname would be, A:testingonetwothree.txt

EXAMPLE | New Directory:


The $> New-item CmdLet is specific for creating files & directories. This is somewhat unique, as the Linux Shell BASH implements the $> mkdir command, but it only makes directories, not files. BASH demonstrates that a SHELL doesn’t have to have a command thats specificly for file creation, however; that’s not to say that having a file-creation command doesn’t have any benifits. But, in Windows, you can, and you should, use the New-Item CmdLet for creating directories.

Here is how to create a directory when using PowerShell:

New-Item -Path 'Z:sum-directory' -ItemType Directory

This command creates a new directory named sum-directory. The directory is located in the drive-letter Z:, and the directory’s full pathname would be Z:sum-directory


FOR MORE INFORMATION ABOUT THIS TOPIC, PLEASE VISIT:

https://learn.microsoft.com/en-us/powershell/scripting/samples/working-with-files-and-folders?view=powershell-7.1#creating-files-and-folders

Cover image for Use "touch" command in windows 10.

Gautham Vijayan

Unix commands like touch will not work in windows system so people have gotten smart and have figured out a way to touch(create) a file in the terminal in windows.

There is a npm package called touch-cli which will allow us to use touch command.

Open up your terminal and paste the following code.

npm install touch-cli -g

We install the touch-cli globally so we can use it in any folder.

Now below we can see the touch-cli in action.

Screen Recording 2020-11-20 at 08.44.53.16 PM

Thank you for reading!

If you like this article, Unicorn this one! Heart/Like this one and save it for reading it later.

My Other Articles:

  • Universal CSS properties everyone must know

  • Create-react-app

  • Git for beginners

  • Change headers in react with react-helmet

  • Know How to apply box-shadow on all four sides.

  • Simple CSS Selectors.

  • CSS Pseudo Elements.

  • CSS Pseudo Classes For Beginners.

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

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

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

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

param
(
  [Parameter(Mandatory=$true)][string]$SourcePath,
  [Parameter(Mandatory=$true)][string]$TargetPath
)

(GI -LiteralPath $TargetPath).CreationTime  = (GI -LiteralPath $SourcePath).CreationTime
(GI -LiteralPath $TargetPath).LastWriteTime = (GI -LiteralPath $SourcePath).LastWriteTime

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

%~dp0ffmpeg -i "%~1" ACTION "%~1-output.mp4"

CHCP 65001 > nul && PowerShell -ExecutionPolicy ByPass -File "%~dp0CLONE-FILE-DATE.PS1" "%~1" "%~1-output.mp4"

Я думаю, что 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:

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:

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.

— or even if you don’t want make it hard you can Just install Windows Subsystem for Linux (WSL). Then, type.

Quotes are not needed.

команда touch в windows

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:

команда touch в windows

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

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

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

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

Источник

Windows-эквивалент команды Linux «Сенсорный»?

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

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

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

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

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

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

Запятые указывают на пропуск параметра Destination.

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

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

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

Если все, что вам нужно, это изменить дату последнего изменения файла (в моем случае):

ОБНОВИТЬ

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

Вот объяснение Technet таинственных ‘+’ и запятых:

Запятые указывают на пропуск параметра Destination.

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

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

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

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

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

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

Для обновления меток времени (игнорируя другие функции touch ) я бы выбрал:

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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

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

30 ответов

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

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

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

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

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

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

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

UPDATE

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Файл fsutil createnew new.txt 0

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

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

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

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

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

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

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

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

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

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

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

Источник

Equivalent of Linux `touch` to create an empty file with PowerShell [duplicate]

Is there an equivalent of touch in PowerShell?

For instance, in Linux I can create a new empty file by invoking:

So is there a programmatic way in PowerShell to do this?

I am not looking to exactly match behaviour of touch, but just to find the simplest possible equivalent for creating empty files.

14 Answers 14

Using the append redirector «>>» resolves the issue where an existing file is deleted:

To create a blank file:

To update the timestamp of a file:

Here is a version that creates a new file if it does not exist or updates the timestamp if it does exist.

In PowerShell you can create a similar Touch function as such:

команда touch в windows

There are a bunch of worthy answers already, but I quite like the alias of New-Item which is just: ni

You can also forgo the file type declaration (which I assume is implicit when an extension is added), so to create a javascript file with the name of ‘x’ in my current directory I can simply write:

3 chars quicker than touch!

команда touch в windows

I prefer Format-Table for this task (mnemonic file touch):

To work with non-empty files you can use:

I chose this because it is a short command that does nothing in this context, a noop. It is also nice because if you forget the redirect:

instead of giving you an error, again it just does nothing. Some other aliases that will work are Format-Custom ( fc ) and Format-Wide ( fw ).

I put together various sources, and wound up with the following, which met my needs. I needed to set the write date of a DLL that was built on a machine in a different timezone:

Of course, you can also set it for multiple files:

It looks like a bunch of the answers here don’t account for file encoding.

I just ran into this problem, for various other reasons, but

both produce a UTF-16-LE file, while

produces a UTF-8 file.

gives you a UTF-8-BOM file, while

this example does not update the timestamp for some reason, but this one does:

Although it does have the side effect of appending «foo» to the end of the file.

If you are unsure about what encoding you have, I’ve found VS-Code has a nifty feature where at the bottom right hand corner it says what the encoding is. I think Notepad++ also has a similar feature.

Источник

Русские Блоги

Командная строка Windows, команда ls / cat / mv / touch и использование веб-сайта diverhell.com

Командная строка command ls

ls Да list Сокращение, означает список всех видимых файлов в текущем каталоге, как показано на рисунке:
команда touch в windows
Это связано сdirТот же эффект, за исключением того, что папки в текущем каталоге будут отображаться разными цветами и добавляться с помощью «/»

команда touch в windows

ФИО:concatenate files and print on the standard output

Средства объединения файлов и вывода

Добавьте text4.txt text5.txt text6.txt в файл text3.txt

Примечание: только добавить без перезаписи
команда touch в windows10、cat text4.txt text5.txt text6.txt>text3.txt

Добавьте text4.txt text5.txt text6.txt в файл text3.txt и перезапишите исходный текст

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

mv Да move Сокращение значенияПереместить файл, Как показано:

1. mv уже существует имя файла 1 уже существует имя файла 2

Например: mv text5.txt text6.txt
команда touch в windows
Результат: текст существующего имени файла 2 перезаписывается текстом существующего имени файла 1, а затем существующее имя файла 1 удаляется.

2. mv уже существует имя файла 1 не существует имя файла 2

Например: mv text6.txt text7.txt
команда touch в windowsРезультат: существующее имя файла 1 переименовано в несуществующее имя файла 2, т.е. text6.txt переименован в text7.txt

3. папка с именем файла mv

Такие как: mv text7.txt text
команда touch в windowsРезультат: файл перемещается в папку, т.е. text7.txt перемещается в текст папки

4. папка mv *

То есть все файлы в текущей папке перемещаются в указанную папку партиями
команда touch в windowsКомандная строка командной строки

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

Использование пояснениеhellhell.com

Этот веб-сайт эквивалентен онлайн-API, специально для запроса инструкций командной строки
команда touch в windowsкоманда touch в windowsover.

Источник

Понравилась статья? Поделить с друзьями:
  • Total коммандер для windows 7 скачать бесплатно
  • Total war warhammer ii не запускается на windows 10
  • Total war warhammer 2 где лежат сохранения windows 10
  • Total war three kingdoms не запускается на windows 10
  • Total war three kingdoms вылетает при запуске windows 10