展平文件夹结构并创建索引

Flatten folder structure and create index

有些人喜欢使用长文件夹名称和深文件夹结构。当您在线使用 OneDrive/SharePoint 并将长路径与 Windows 同步时,这尤其痛苦。

因此我正在寻找一种方法来缩短这些路径并保留其含义,尤其是在归档文件和文件夹时。

基本在尝试改造:

VeryLongPath\AnotherLongFolderPath\AndAnotherOne\VeryLongFilename.xlsx

进入:

1.xlsx

并生成如下索引文件:

1 VeryLongPath
    2 AnotherLongFolderPath
        3 AndAnotherOne
            4 VeryLongFilename.xlsx

您可以创建一个助手 class 来跟踪各个标签:

class PathLabelIndexer
{
  # This will hold the label translations, [string] -> [int]
  [hashtable]$_terms = @{}

  # This will keep track of how many distinct labels we've encountered
  [int]$_length = 0

  # Transforms a path into index values
  [string] Transform([string]$Path){
    return @($Path.Split('\') |%{
      if($this._terms.ContainsKey($_)){
        # If we already have a translation for $_, use that!
        $this._terms[$_]
      }
      else {
        # No existing translation found, add a new one
        ($this._terms[$_] = $this._length++)
      }
    }) -join '\'
  }

  # Produces the index needed to translate them back to labels
  [string[]] GetIndex(){
    # Since $_length starts at 0, a sorted array of the index values will give us the correct mapping
    return [string[]]@($this._terms.GetEnumerator() |Sort Value |ForEach-Object Key)
  }
}

现在您可以:

PS ~> $indexer = [PathLabelIndexer]::new()
PS ~> $indexer.Transform('VeryLongPath\AnotherLongFolderPath\AndAnotherOne\VeryLongFilename.xlsx')
0

要反过来,只需生成结果索引并再次查找各个标签:

PS ~> $index = $indexer.GetIndex()
PS ~> $index['0'.Split('\')] -join '\'
VeryLongPath\AnotherLongFolderPath\AndAnotherOne\VeryLongFilename.xlsx