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