Powershell Copy-Item 但仅复制更改的文件
我正在尝试递归一个目录并将其从 A 复制到 B。这可以通过以下方式完成:
Copy-Item C:\MyTest C:\MyTest2 –recurse
我希望能够只复制新文件(存在于 src 中但不存在于 dest 中的文件)并且也只复制文件这可能是基于 CRC 检查而不是日期时间戳而改变的。
$file = "c:\scripts"
param
(
$file
)
$algo = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
$stream = New-Object System.IO.FileStream($file, [System.IO.FileMode]::Open)
$md5StringBuilder = New-Object System.Text.StringBuilder
$algo.ComputeHash($stream) | `
% { [void] $md5StringBuilder.Append($_.ToString("x2")) }
$md5StringBuilder.ToString()
$stream.Dispose()
这段代码为我提供了对特定文件的 CRC 检查...我只是不确定如何将两个脚本放在一起才能真正满足我的需要。 我也不知道上面的 CRC 检查是否实际上是执行此操作的正确方法。
有人有任何见解吗?
I am trying to recurse through a directory and copy it from A to B. That can be done with the following:
Copy-Item C:\MyTest C:\MyTest2 –recurse
I want to be able though to only copy new files (ones that exist in src but not dest) and also only copy files that may have changed based off a CRC check and not a datetime stamp.
$file = "c:\scripts"
param
(
$file
)
$algo = [System.Security.Cryptography.HashAlgorithm]::Create("MD5")
$stream = New-Object System.IO.FileStream($file, [System.IO.FileMode]::Open)
$md5StringBuilder = New-Object System.Text.StringBuilder
$algo.ComputeHash($stream) | `
% { [void] $md5StringBuilder.Append($_.ToString("x2")) }
$md5StringBuilder.ToString()
$stream.Dispose()
This code gives me a CRC check on a specific file...I am just not sure how to put the two scripts together to really give me what I need. I also don't know if the CRC check above is actually the correct way of doing this.
Does anyone have any insight?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我找到了一个解决方案......但不确定从性能角度来看它是最好的:
I found a solution...but not sure it is the best from a performance perspective:
它有点长,但它的工作效果令人钦佩 - 可以扩展以查找文件的存档位 ---a-- 属性。 无论如何,对于某人来说可能是一个合理的起点。
It is a bit long in the tooth but it does the job admirably - could be extended to look for archive bit ---a--- attribute of the file. Anyway might be a reasonable starting point for someone.
尝试下面的方法。 它将在 7 天内检查任何内容,您可以设置或不设置。 但是,它会查找任何不存在的文件或过去 7 天内更新的任何内容。
Try the below. It will check for anything within 7 days, which you can set or not. But, it will find any files that don't exist or anything updated within the past 7 days.
这两个都是 powershell 的可靠答案,但利用 Robocopy 可能会容易得多(MS 提供了强大的复制应用程序)。
会完成同样的事情。
Both of those are solid answers for powershell, but it would probably be far more easy to just leverage Robocopy (MS Supplied robust copy application).
would accomplish the same thing.
以下是一些如何使脚本更易于维护的指南。
将原始脚本转换为过滤器。
然后简单地过滤所有更新的文件并复制它们。
或者您可以创建另一个生成子目录的函数
Here is some of the guidelines how you can your script to be more maintainable.
Conver the original script as a filter.
Then simply filter all files that are updated and copy them.
Or you can create another function that generates sub directory