Search code examples
powershellnullcopysemaphorelast-modified

Powershell, copy modified time of file to semaphore file


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.


Solution

  • 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