a krishna
a krishna

Reputation: 85

Get a specific folder name from path

How to get the 4th folder name and store it in a variable while looping through the files stored in a parent folder. For example, if the path is

C:\ParentFolder\Subfolder1\subfolder2\subfolder3\file.extension 
C:\ParentFolder\Subfolder1\subfolder2\subfolder4\file.extension 
C:\ParentFolder\Subfolder1\subfolder2\subfolder5\file.extension 

then subfolder2 name should be stored in a variable. Can any one please help me on this?

get-childitem $DirectorNane -Recurse | Where-Object{!($_.PSIsContainer)} | % {

    $filePath = $_.FullName

    #Get file name
    $fileName = Split-Path -Path $filePath -Leaf
}   $FileI = Split-Path -Path $filePath -Leaf

Thanks in advance!

Upvotes: 2

Views: 6789

Answers (2)

Bryce McDonald
Bryce McDonald

Reputation: 1870

You can use the -split operator on the $filePath variable to get what you want.

$split = $filePath -split '\\'
$myvar = $split[3]

We use the double backslash to split with, because the first slash escapes the slash character to split the path by. Then, we can reference the part of the path we want in the array that gets generated in the "split" variable.

Additionally, you can solve this with a one liner using the following code:

$myvar = $filepath.split('\')[3]

This would ensure that you're always getting the fourth element in the array, but is a little less flexible since you can't specify what exactly you want based on conditions with additional scripting.

Upvotes: 7

Bill_Stewart
Bill_Stewart

Reputation: 24525

If you are asking how to get the parent directory of the directory containing a file, you can call Split-Path twice. Example:

$filePath = "C:\ParentFolder\Subfolder1\subfolder2\subfolder3\file.extension"
$parentOfParent = Split-Path (Split-Path $filePath)
# $parentOfParent now contains "C:\ParentFolder\Subfolder1\subfolder2"

Upvotes: 0

Related Questions