Melab
Melab

Reputation: 2812

How do I get directory depth in PowerShell 3.0?

I need to find out how far down the directory structure inside a working directory goes. If the layout is something like

Books\
Email\
Notes\
    Note 1.txt
    Note 2.txt
HW.docx

then it should return 1, because the deepest items are 1 level below. But if it looks like

Books\
Photos\
Hello.c

then it should return 0, because there is nothing deeper than the first level.

Upvotes: 1

Views: 2212

Answers (2)

mjolinor
mjolinor

Reputation: 68243

It's not as pretty, and arguably not as "Posh" as Keith's, but I suspect it might scale better.

$depth_ht = @{}
(cmd /c dir /ad /s) -replace '[^\\]','' |
 foreach {$depth_ht[$_]++}

 $max_depth = 
  $depth_ht.keys |
   sort length |
   select -last 1 |
   select -ExpandProperty length

 $root_depth =
  ($PWD -replace '[^\\]','').length

 ($max_depth -$root_depth)

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 201622

Something like this should do the trick in V3:

Get-ChildItem . -Recurse -Name | Foreach {($_.ToCharArray() | 
    Where {$_ -eq '\'} | Measure).Count} | Measure -Maximum | Foreach Maximum

Upvotes: 1

Related Questions