1

I would like to use powershell to copy the modified time from a file to a new file but have the content of the file be nothing. In command prompt I would use the following syntax:

copy /nul: file1.ext file2.ext

The second file would have the same modified time as the first file, but the content would be 0 bytes.

The intention is to use the syntax to run a script to check the folder, find file1 and create file2.

dizzi90
  • 80
  • 8
  • possible duplicate of [PowerShell open a file for write only (for Lock) and doing 'touch' so to change the file's Last Modified Date](http://stackoverflow.com/questions/26156715/powershell-open-a-file-for-write-only-for-lock-and-doing-touch-so-to-change) – Matt Dec 23 '14 at 13:14

1 Answers1

1

If you are using PowerShell v4.0, you can do a pipeline chain using -PipelineVariable and have something like this:

New-Item -ItemType File file1.txt -PipelineVariable d `
    | New-Item -ItemType File -Path file2.txt `
    | ForEach-Object {$_.LastWriteTime = $d.LastWriteTime}

In PowerShell v3.0 (or less) you can just use ForEach-Object loops:

New-Item -ItemType File -Path file1.txt `
    | ForEach-Object {(New-Item -ItemType File -Path file2.txt).LastWriteTime = $_.LastWriteTime}

I understand that is a little verbose. Cutting it down to aliases would be easy:

ni -type file file1.txt | %{(ni -type file file2.txt).LastWriteTime = $_.LastWriteTime}

Or you could wrap it in a function:

Function New-ItemWithSemaphore {
    New-Item -ItemType File -Path $args[0] `
    | ForEach-Object {(New-Item -ItemType File -Path $args[1]).LastWriteTime = $_.LastWriteTime}
}

New-ItemWithSemaphore file1.txt file2.txt

If you are using existing files, this will work by just getting the item based on a given path:

Function New-FileSemaphore {
    Get-Item -Path $args[0] `
    | ForEach-Object {(New-Item -ItemType File -Path $args[1]).LastWriteTime = $_.LastWriteTime}
}

New-FileSemaphore file1.txt file2.txt
SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59