Kiril
Kiril

Reputation: 6229

Flatten folder structure and create index

Some people like to use long folder names and deep folder structures. This is especially painful when you use OneDrive/SharePoint Online and sync long paths with Windows.

Hence I am looking for an approach to shorten those paths and keep the meaning, especially when archiving files and folders.

Basically trying to transform:

VeryLongPath\AnotherLongFolderPath\AndAnotherOne\VeryLongFilename.xlsx

Into:

1\2\3\4.xlsx

And generating the following index file:

1 VeryLongPath
    2 AnotherLongFolderPath
        3 AndAnotherOne
            4 VeryLongFilename.xlsx

Upvotes: 0

Views: 277

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174660

You could create a helper class to track the individual labels:

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)
  }
}

Now you can do:

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

To get the reverse, simply produce the resulting index and look up the individual labels again:

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

Upvotes: 2

Related Questions