10

I use the following line in my script to return all the paths of all folders at the $folder location.

dir -recurse $folder|?{$_.PSIsContainer}|select -ExpandProperty FullName

This works. But: I only need the fourth element of each path.

I've tried adding |{$_.Split("\")}[3]}with the [3] in various places but I am getting an error with the split command, that Expressions are only allowed as the first element of a pipeline.

I've tried putting brackets around various sections, and putting the whole expression into brackets and into a split but I can't seem to find a way to attach the split to any part of the pipe... Is there another way, perhaps?

1 Answer 1

10

You are almost there. You need to put your code within the Foreach-Object cmdlet:

Get-ChildItem -recurse $folder|
    Where-Object {$_.PSIsContainer}|
    Select-Object -ExpandProperty FullName |
    ForEach-Object {            
        $_.Split("\")[3]        
    }
3
  • is there a slicker way to do this if you know that only one object is going through the pipe? Or do you always have to use foreach? Nov 10, 2020 at 18:30
  • @MaxCascone If you don't care about the property heading, you can do it like this: et-ChildItem -recurse $folder| Where-Object {$_.PSIsContainer}| Select-Object {$_.FullName.Split("\")[3]} Nov 10, 2020 at 18:34
  • that's good too, although i kind of forgot why i came here in the first place, which was looking for a more "correct" way to do (some function).split('') . Which, actually might be the best way if you are sure there will only ever be 1 object coming out. That might not even be a requirement. I just felt the parentheses were 'messy', although the pipe-select-foreach pattern might be messier. This is an example of style over function. Nov 10, 2020 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.