Rouven H
Rouven H

Reputation: 71

PowerShell get name of folders in a path

I try to figure out some names of folders in a path. For example:

C:\folder1\folder2\folder3\folder4\folder5\folder6

how can i get the name of folder 2 or 3? Just as a String without any Slashes.

Upvotes: 1

Views: 2338

Answers (3)

mohamed saeed
mohamed saeed

Reputation: 303

$Path = "C:\f1\f2\"
$pspath = Get-ChildItem $Path
$namef2 = $pspath.Parent.Name
$namef2
$namef2.GetType().Name
$namef1 = $pspath.Parent.Parent.Name
$namef1
$namef1.GetType().Name

Upvotes: -1

Hackoo
Hackoo

Reputation: 18827

You can use .Split("\") to the path folder

$pathfolder = "C:\folder1\folder2\folder3\folder4"
$pathfolder.Split("\")

cls
$pathfolder = "C:\folder1\folder2\folder3\folder4"
$A = $pathfolder.Split("\")
$Count = $pathfolder.Split("\").Count

For ($i=1; $i -le $Count+1; $i++) {
    echo $A[$i]
}

$pathfolder = "C:\folder1\folder2\folder3\folder4"
$A = $pathfolder.Split("\")

echo "The folder number 2 with name : " $A[2]
echo "The folder number 3 with name : " $A[3]

Upvotes: 2

zackchadwick
zackchadwick

Reputation: 111

You should be able to use Get-ChildItem with the Directory and Depth command.

Something like

Get-ChildItem -Directory -Depth 6

This should return all Directory Names that are in the subfolder.

You could then pipe this into Select to grab just the name and parent directory.

Get-ChildItem -Directory -Depth 6 | Select Name, Parent

Edit

If you want to go in the reverse direction because you have a file in folder 6 and want the name of folder 2 you could do something like this.

(get-item FileIn6.txt).directory.parent.parent.parent.parent | select Name

So if FileIn6.txt is a file sitting in folder 6, you get item and then grab the directory property, and the parent of that, parent of next, etc. Hopefully that makes sense.

Upvotes: 0

Related Questions