Powershell,将文件的修改时间复制到信号量文件

时间:2014-12-23 11:45:57

标签: powershell null copy semaphore last-modified

我想使用powershell将修改时间从文件复制到新文件,但文件内容没有任何内容。 在命令提示符中,我将使用以下语法:

copy /nul: file1.ext file2.ext

第二个文件的修改时间与第一个文件相同,但内容为0个字节。

目的是使用语法运行脚本来检查文件夹,找到file1并创建file2。

1 个答案:

答案 0 :(得分:1)

如果您使用的是PowerShell v4.0,则可以使用-PipelineVariable执行管道链,并具有以下内容:

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

在PowerShell v3.0(或更低版本)中,您可以使用ForEach-Object循环:

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

我明白这有点冗长。将其简化为别名很容易:

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

或者你可以把它包装在一个函数中:

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

如果您使用现有文件,只需根据给定路径获取项目即可:

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