Path cmdlets: 3 getting the folder

One thing you may have to do is find the folder name of the container holding the file.  This is the last folder on the path BUT you don’t know how long the path is.

One possibility is to use a trick with array indicies


PS> $path = "c:\scripts\utils\accelerators.ps1" -split "\\"
PS> $path

PS> $path[-1]

PS> $path[-2]


Split the path using the spilt operator -  need to use \\ as \ is a regex escape character.

-1 always returns the last element in the array which is the file name so

-2 returns the next to last which is the folder


The easier way is like this

PS> Split-Path -Path (Split-Path -Path c:\scripts\utils\accelerators.ps1 -Parent) -Leaf


Nest split-path in the path of split-path. The inner one returns the full path of the files parent container and the outer one returns the leaf which is the last folder on the path.

Leave a Reply