PowerShell: How to Get File Name from Path


You can use the following methods in PowerShell to get a file name from a path:

Method 1: Get File Name from Path (With Extension)

(Get-ChildItem $my_file_path).Name

This particular example gets the file name (with extension) from the path specified by the $my_file_path variable.

Method 2: Get File Name from Path (Without Extension)

(Get-ChildItem $my_file_path).BaseName

This particular example gets the file name (without extension) from the path specified by the $my_file_path variable.

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

Example 1: How to Get File Name from Path (With Extension)

Suppose we have a file located at the following path:

  • c:\users\bobbi\data1\players.txt

Suppose that we would like to get only the file name (with extension) from this path.

We can use the following syntax to do so:

$my_file_path = 'c:\users\bobbi\data1\players.txt'
(Get-ChildItem $my_file_path).Name

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

PowerShell get file name with extension from path

Notice that this returns players.txt, which represents the file name with the extension.

Example 2: How to Get File Name from Path (Without Extension)

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

  • c:\users\bobbi\data1\players.txt

Suppose that we would like to get only the file name (without the extension) from this path.

We can use the following syntax to do so:

$my_file_path = 'c:\users\bobbi\data1\players.txt'
(Get-ChildItem $my_file_path).BaseName

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

PowerShell get file name without extension from path

Notice that this returns players, which represents the file name without the extension.

Related Tutorials

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

PowerShell: How to Get Last Folder in Path
PowerShell: How to Check if Folder Exists
PowerShell: How to Use Get-ChildItem to Return Folders Only

Leave a Reply