Search code examples
powershellsubdirectorydepth

Powershell - Find # of nested folders in long file path of a directory


Can anyone help me w/ a code puzzle in powershell? I'm trying to look at a specific directory on several remote servers, and find the deepest nested subfolder in that directory and then count number of parent folders. Pseudo code below.

  1. $servers = get-content (list of servers) and $path = (targetdir on remote machine)
  2. for each $s in $servers:
  3. find the longest path
  4. count the # of \ (to identify # of subfolders)
  5. Write output to file $Servername $countOfNestedFolders

Sorry I'm just good enough w/ posh to be a little dangerous.


Solution

  • here's a slight variant of the "count the path parts" solutions. [grin] it counts the delimiters. if your paths are UNC paths OR local paths, this will still give you the deepest nested dir.

    however, it will not work with mixed UNC [\\SysName\ShareName] and local [c:\] paths.

    also, it does not remove the starting dir from the result.

    also also, i am unsure how you want to count number of parent folders. so i just posted the delimiter count.

    what it does ...

    • sets the top dir to work from
    • gets the dir delimiter char
    • creates a regex escaped version of that char
    • grabs all the dirs in the target dir tree
    • sorts [in descending order] them by the string length of what is left over when you remove everything except the dir delimiters
    • grabs the 1st of those dirs
    • displays the .FullName of that dir
    • displays the number of dir delimiters in the above string

    the code ...

    $TargetTopDir = $env:APPDATA
    $DirDelim = [System.IO.Path]::DirectorySeparatorChar
    $RegexDD = [regex]::Escape($DirDelim)
    
    $DirList = Get-ChildItem -LiteralPath $TargetTopDir -Directory -Recurse
    
    $DeepestNestedDir = ($DirList |
        Sort-Object {$_.FullName -replace "[^$RegexDD]"} -Descending)[0]
    
    $DeepestNestedDir.FullName
    'DirDelimCount = {0}' -f ($DeepestNestedDir.FullName -replace "[^$RegexDD]").Length
    

    output ...

    C:\Users\MyUserName\AppData\Roaming\Thunderbird\Profiles\shkjhmpc.default\extensions\{e2fda1a4-762b-4020-b5ad-a41df1933103}\chrome\calendar-gd\locale\gd\calendar\dialogs
    DirDelimCount = 15