Often you may want to extract only the extension from a file name using PowerShell.
There are two common ways to do so:
Method 1: Get File Extension from Disk
$my_file = Get-Item "c:\users\bobbi\nba_data.xlsx"
$my_file.Extension
This particular example uses the Get-Item cmdlet to retrieve a file located at a specific path, then uses the Extension property to extract only the extension from the file name.
Method 2: Get File Extension from String
$my_file = "c:\users\bobbi\nba_data.csv" [System.IO.Path]::GetExtension($my_file)
This particular example uses [System.IO.Path]::GetExtension to directly extract the extension of a file when the file name is stored as a string.
The following example shows how to use this syntax in practice.
Example 1: Get File Extension from Disk Using PowerShell
Suppose that we have a file located at the following path:
- C:\Users\bobbi\nba_data.xlsx
Suppose that we would like to extract only the file extension from this path.
One way to do so is by using Get-Item to retrieve the file and then by using the Extension property to extract only the extension:
$my_file = Get-Item "c:\users\bobbi\nba_data.xlsx"
$my_file.Extension
The following screenshot shows how to use this syntax in practice:

We can see that this returns .xlsx, which represents just the extension of the file.
Example 2: Get File Extension from String Using PowerShell
Suppose that we have a file location stored in a string in PowerShell:
- “c:\users\bobbi\nba_data.xlsx”
Suppose that we would like to extract only the file extension from this string.
One way to do so is by using [System.IO.Path]::GetExtension to directly extract the extension of the file:
$my_file = "c:\users\bobbi\nba_data.xlsx"
[System.IO.Path]::GetExtension($my_file)
The following screenshot shows how to use this syntax in practice:

We can see that this returns .xlsx, which represents just the extension of the file.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Rename File Extension of Multiple Files
PowerShell: How to Add Date to File Name
