powershell 为什么这个ForEach循环这么慢

bttbmeg0  于 2023-03-23  发布在  Shell
关注(0)|答案(1)|浏览(180)

我有目录字符串列表(百万)需要缩短以满足特定长度(MaxPathLength),一旦我删除了额外的字符,我需要将它们添加到另一个数组列表或文件中。重要的是,我不修改前2级目录名称,因此是$topLevel = "{0}\{1}\{2}" -f $SubDir.Split("\")。将这部分移出循环是不可能的,因为有成千上万的顶级2级目录。
我尝试了使用NewPathList(长字符串)数组来管道到ForEach和从文件中阅读,两者都非常慢。
我还尝试了ForEach-Object -parallel进行适当的修改,它也非常慢。

$NewPathList | Foreach {$SubDir = $_
  [int]$Chars2Remove  = $SubDir.length - $MaxPathLength
  If (($SubDir.Length -gt $MaxPathLength))
  {
      [string]$TopLevel           = "{0}\{1}\{2}" -f $SubDir.Split("\")
      [string]$Path2Shorten       = $null
      [string]$Path2Shorten       = $SubDir -replace([regex]::Escape($TopLevel))
      For($c=1;$c -le $Chars2Remove;$c++)
          {
              $MostRecurringChar     = ($Path2Shorten.GetEnumerator() | Group-Object -NoElement| Sort-Object count -Descending | Select-Object -First 1).Name
              $RandIndex = ([regex]::matches($Path2Shorten,'[.$MostRecurringChar]').index | Select-Object -Last 1) # | Get-Random -Count 1
              $ShortString = $Path2Shorten.Remove($RandIndex,1)
          }

          [String]$SubDir2Create      = $TopLevel  + $ShortString
  }
  else {
      [String]$SubDir2Create      = $null
      [String]$SubDir2Create      = $SubDir.ToString()
  }

  $ShortPathList.Add($SubDir2Create)

}

2wnc66cl

2wnc66cl1#

使用.Substring()而不是遍历字符:

$NewPathList | foreach {
    $SubDir = $_
    [int]$Chars2Remove  = $SubDir.length - $MaxPathLength
    if ($SubDir.Length -gt $MaxPathLength){
        [string]$TopLevel = "{0}\{1}\{2}" -f $SubDir.Split("\")
        [string]$Path2Shorten       = $null
        [string]$Path2Shorten       = $SubDir -replace([regex]::Escape($TopLevel))
        [int]$RemainingLength = $MaxPathLength - $TopLevel.Length
        $ShortString = $Path2Shorten.Substring(($Path2Shorten.Length - $RemainingLength))
        [String]$SubDir2Create = $TopLevel + $ShortString
    }
} else {
    [String]$SubDir2Create      = $null
    [String]$SubDir2Create      = $SubDir.ToString()
}
$ShortPathList.Add($SubDir2Create)

相关问题