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



我想使用 powershell 将修改时间从文件复制到新文件,但文件的内容却一无所有。在命令提示符下,我将使用以下语法:

copy /nul: file1.ext file2.ext

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

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

如果你使用的是 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

最新更新