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

Powershell,将文件的修改时间复制到信号量文件,powershell,null,copy,semaphore,last-modified,Powershell,Null,Copy,Semaphore,Last Modified,我想使用powershell将修改后的时间从一个文件复制到一个新文件,但该文件的内容为空。 在命令提示符中,我将使用以下语法: copy /nul: file1.ext file2.ext 第二个文件的修改时间与第一个文件相同,但内容为0字节 其目的是使用语法运行脚本以检查文件夹、查找文件1和创建文件2。如果您使用的是PowerShell v4.0,则可以使用-PipelineVariable执行管道链,并具有如下功能: New-Item -ItemType File file1.txt -P

我想使用powershell将修改后的时间从一个文件复制到一个新文件,但该文件的内容为空。 在命令提示符中,我将使用以下语法:

copy /nul: file1.ext file2.ext
第二个文件的修改时间与第一个文件相同,但内容为0字节


其目的是使用语法运行脚本以检查文件夹、查找文件1和创建文件2。

如果您使用的是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对象循环:

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
可能重复的