PowerShell: How to Get Last Folder in Path


You can use the following methods in PowerShell to get the last folder in a path:

Method 1: Get Last Folder in Path

Split-Path (Split-Path $source -Parent) -Leaf

This particular example gets the last folder from the path specified in the $source variable.

Method 2: Get Last N Folders in Path

$source.split("\")[-3..-2] -join "\"

This particular example gets the last 2 folders in the path specified in the $source variable.

Note: This formula works by splitting the file path where each backslash occurs, then by selecting the elements that are second to last and third to last in the file path and joining them with a forward slash.

The following examples show how to use each method in practice.

Example 1: Get Last Folder in Path Using PowerShell

Suppose we have a file located at the following path:

  • c:\users\bobbi\data4\basketball_data.csv

Suppose that we would like to get the name of the last folder (data4) in this particular path.

We can use the following syntax to do so:

$source = "c:\users\bobbi\data4\basketball_data.csv"
Split-Path (Split-Path $source -Parent) -Leaf 

The following example shows how to use this syntax in practice:

PowerShell get last folder in path

Notice that this returns data4, which is indeed the last folder in the path that we specified.

Example 2: Get Last N Folders in Path Using PowerShell

Once again, suppose we have a file located at the following path:

  • c:\users\bobbi\data4\basketball_data.csv

Suppose that we would like to get the name of the last two folders (bobbit\data4) in this particular path.

We can use the following syntax to do so:

$source = "c:\users\bobbi\data4\basketball_data.csv"
$source.split("\")[-3..-2] -join "\"

The following example shows how to use this syntax in practice:

PowerShell get last two folders in path

Notice that this returns bobbi\data4, which represents the last two folders in the path that we specified.

Feel free to change the starting and ending values within the brackets to extract a different number of folders from the path.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Get Last Item in Array
PowerShell: How to Get Last Character of String
PowerShell: How to List Files in Directory by Date

Leave a Reply