【问题标题】:Powershell, copy modified time of file to semaphore filePowershell,将文件的修改时间复制到信号量文件
【发布时间】:2014-12-23 11:45:57
【问题描述】:

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

copy /nul: file1.ext file2.ext

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

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

【问题讨论】:

标签: powershell null copy semaphore last-modified


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多