Skip to main content

How to Get File Extension Using PowerShell

• 3 min read
powershell file extension path get-item

There are several ways in PowerShell to get file extensions.

Method 1: Using the Split-Path and Split() method

# specify the file path
$filePath = "C:\temp\log\my_log.txt"

# Get the filename with extension
$fileNameWithExtension = Split-Path -Path $filePath -Leaf

# Split the filename and extension using the Split() method
$fileExtension = $fileNameWithExtension.Split(".")[1]

# output the file extension
Write-Output $fileExtension

This example uses the Split-Path cmdlet and Split() method to extract the file extension and output to the console.

Method 2: Using the [System.IO.Path] .Net class

# specify the file path
$filePath = "C:\temp\log\my_log.txt"

# Get the extension
$fileExtension = [System.IO.Path]::GetExtension($filePath)

# output the file extension
Write-Output $fileExtension

This example uses the [System.IO.Path] .Net class and its method GetExtension() to get file extension.

Method 3: Using the Get-ChildItem cmdlet

# specify the file path
$filePath = "C:\temp\log\my_log.txt"

# Get the file extension
$fileExtension = (Get-ChildItem -Path $filePath -File).Extension

# output the file extension
Write-Output $fileExtension

This example uses the Get-ChildItem cmdlet to extract the file extension.

Method 4: Using the Get-Item cmdlet

# specify the file path
$filePath = "C:\temp\log\my_log.txt"

# Get the file extension
$fileExtension = (Get-Item -Path $filePath).Extension

# output the file extension
Write-Output $fileExtension

This example uses the Get-Item cmdlet to extract the file extension.

Get File Extension Using Split-Path and Split() in PowerShell

You can use the Split-Path cmdlet to get the filename with extension using its -Leaf parameter and then use the Split() method to extract the file extension.

In this script, the $filePath variable stores the path to the file. The Split-Path cmdlet in PowerShell gets the filename with extension using its -Leaf parameter and stores it in the $fileNameWithExtension variable.

Finally, we call the Split() method over the $fileNameWithExtension variable to extract the file extension and output to the console using the Write-Output cmdlet.

Conclusion

I hope the above article on getting file extension using PowerShell is helpful to you.


File Information & Properties

File Path & Navigation

  • PowerShell Test-Path - Check if path exists
  • PowerShell Get-Item - Get item objects
  • PowerShell Split-Path - Extract path components

File Management Operations

Date & Time Operations

Data Selection & Filtering

Display & Formatting

Control Flow & Logic

Variables & Collections

Output & Export

Storage & Disk Operations

Functions & Automation

Comprehensive Guides