Search code examples
powershellpipeline

Can I collapse this into a single line of code using the pipeline?


I'm querying a highly structured file system. I need to look at the nodes that are at the 14th level of the tree. I've come up with the following based on some other posts on querying filesystems and my own research:

$lines = Get-ChildItem "\\ad1hfdahp001\D$\software\anthill\var\artifacts" -Recurse -Force -EA SilentlyContinue |
         Where-Object { $_ -is [System.IO.DirectoryInfo] } |
         Select -ExpandProperty FullName

$paths=@()
foreach ($d in $lines) {
    $a = $d -split "\\"
    if ($a.count -eq 14) {$paths += $d}
}

Is there a way to add the code in the foreach block (or part of it) to the first statement so that $lines only contains the paths with 14 levels? I know this is trivial, but I'm processing a huge amount of data I feel as though adding this as a filter to the pipeline in the first statement would be much more efficient than dumping all the directories into an array and then reprocessing the array to select the 14-level entries.


Solution

  • Sure. Simply add

    ... | Where-Object { @($_ -split '\\').Count -eq 14 }
    

    after the Select-Object.