【问题标题】:Powershell: Get-ChildItem performance to deal with bulk filesPowershell:Get-ChildItem 处理批量文件的性能
【发布时间】:2021-01-22 07:44:52
【问题描述】:

场景是在远程服务器中,共享一个文件夹供 ppl 访问日志文件。 日志文件在老化前会保留大约 30 天,每天会生成大约 1000 个日志文件。 为了问题分析,我需要根据文件时间戳将日志文件复制到自己的机器上。

我之前的策略是:

  1. 使用dir /OD命令获取文件列表,到我的本地PC,到一个文件中
  2. 打开文件,找到时间戳,获取我需要复制的文件列表
  3. 使用 copy 命令复制实际的日志文件

它可以工作,但需要一些手动工作,即第2步我使用notepad++和正则表达式来过滤时间戳

我尝试使用 powershell 作为:

Get-ChildItem -Path $remotedir | where-object {$_.lastwritetime -gt $starttime -and $_lastwritetime -lt $endtime } |foreach {copy-item $_.fullname -destination .\}

但是使用这种方法需要几个小时和几个小时并且没有文件被复制,而与 dir 解决方案相比,生成文件列表大约需要 7-8 分钟,而不是复制本身需要一些时间而不是几个小时

我猜大部分时间都花在了过滤文件上。我不太清楚为什么 get-childitem 的性能这么差。

如果有什么我可以改变的,你能告诉我吗? 谢谢

【问题讨论】:

  • 您在$.fullname 中缺少_
  • $_lastwritetime在脚本中是这样写的吗?注意缺少的.
  • 最后的 foreach 也是不必要的。
  • 谢谢大家 - 我发现性能问题后在我的个人机器上输入了它。这更像是一个错字。不过谢谢你指出

标签: powershell


【解决方案1】:

对于有很多文件的目录,Get-ChildItem 太慢了。看起来大部分时间都花在枚举目录上,然后通过 'where' 过滤,然后复制每个文件。

直接使用 .net,尤其是 [io.directoryinfo] 与 GetFileSystemInfos() 方法。

例如

$remotedir   = [io.directoryinfo]'\\server\share'
$destination = '.\'
$filemask    = '*.*'
$starttime   = [datetime]'jan-21-2021 1:23pm'
$endtime     = [datetime]'jan-21-2021 4:56pm'

$remotedir.GetFileSystemInfos($filemask, [System.IO.SearchOption]::TopDirectoryOnly) | % {
    if ($_.lastwritetime -gt $starttime -and $_.lastwritetime -lt $endtime){
        Copy-Item -Path $_.fullname -Destination $destination
    }
}

【讨论】:

  • 谢谢它工作正常。所以这就是我所拥有的: 请输入您的目录:: \\remoteserver\dir 请输入您的日期时间:: 2020-12-29 16:00 请输入您的日期时间:: 2021-01-02 16:00开始获取完整列表:01/24/2021 10:43:46 获取完整列表后:01/24/2021 11:11:28 完整副本:01/25/2021 05:22:27 总共复制了 45444 个文件跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多