首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用powershell复制文件并保留原始时间戳

如何使用powershell复制文件并保留原始时间戳
EN

Stack Overflow用户
提问于 2014-02-06 03:48:04
回答 3查看 20.3K关注 0票数 9

我想将一些文件或文件文件夹从一个文件服务器复制到另一个文件服务器。但是,我希望保留原始时间戳和文件属性,以便新复制的文件具有与原始文件相同的时间戳。谢谢您的任何答复。

EN

回答 3

Stack Overflow用户

发布于 2014-02-06 04:15:58

这是一个powershell函数,可以满足你的要求.它完全没有精神状态检查,所以请注意.

代码语言:javascript
运行
复制
function Copy-FileWithTimestamp {
[cmdletbinding()]
param(
    [Parameter(Mandatory=$true,Position=0)][string]$Path,
    [Parameter(Mandatory=$true,Position=1)][string]$Destination
)

    $origLastWriteTime = ( Get-ChildItem $Path ).LastWriteTime
    Copy-Item -Path $Path -Destination $Destination
    (Get-ChildItem $Destination).LastWriteTime = $origLastWriteTime
}

一旦运行了加载,就可以执行如下操作:

代码语言:javascript
运行
复制
Copy-FileWithTimestamp foo bar

(您也可以将其命名为更短的名称,但在选项卡完成后,没有什么大不了的.)

票数 7
EN

Stack Overflow用户

发布于 2014-02-06 05:03:51

下面是如何在时间戳属性权限上进行复制。

代码语言:javascript
运行
复制
$srcpath = 'C:\somepath'
$dstpath = 'C:\anotherpath'
$files = gci $srcpath

foreach ($srcfile in $files) {
  # Build destination file path
  $dstfile = [io.FileInfo]($dstpath, '\', $srcfile.name -join '')

  # Copy the file
  cp $srcfile.FullName $dstfile.FullName

  # Make sure file was copied and exists before copying over properties/attributes
  if ($dstfile.Exists) {
    $dstfile.CreationTime = $srcfile.CreationTime
    $dstfile.LastAccessTime = $srcfile.LastAccessTime
    $dstfile.LastWriteTime = $srcfile.LastWriteTime
    $dstfile.Attributes = $srcfile.Attributes
    $dstfile.SetAccessControl($srcfile.GetAccessControl())
  }
}
票数 2
EN

Stack Overflow用户

发布于 2014-02-06 04:00:16

如果您对两步解决方案没有意见,那么

  • 第一次将文件从源代码复制到dest
  • 循环遍历每个文件;以及每个文件的每个属性。
  • 将属性从源复制到目标

尝试此技术将文件属性从一个文件复制到另一个文件。(我已经用LastWriteTime演示了这一点;我相信您可以将它扩展到其他属性)。

代码语言:javascript
运行
复制
#Created two dummy files
PS> echo hi > foo
PS> echo there > bar

# Get attributes for first file
PS> $timestamp = gci "foo"
PS> $timestamp.LastWriteTime

06 February 2014 09:25:47

# Get attributes for second file
PS> $t2 = gci "bar"
PS> $t2.LastWriteTime

06 February 2014 09:25:53

# Simply overwrite
PS> $t2.LastWriteTime = $timestamp.LastWriteTime

# Ta-Da!
PS> $t2.LastWriteTime

06 February 2014 09:25:47
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21593625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档