Home » How to Get FileName from Path in PowerShell

How to Get FileName from Path in PowerShell

To get a filename from a full file path in PowerShell, you can use the Split-Path cmdlet with the -Leaf parameter.

The following method shows how you can do it with syntax.

Method 1: Extract the filename from a path

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

# Get the filename from the path

$fileName = Split-Path -Path $filePath -Leaf

Write-Output $fileName

This example will extract a file name from a full file path.

The following example shows how to use this method.

Get FileName from Path Using PowerShell

You can extract the filename from a path in PowerShell using the Split-Path cmdlet with the -Leaf parameter.

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

# Get the filename from the path

$fileName = Split-Path -Path $filePath -Leaf

Write-Output $fileName

Output:

PowerShell get filename from path
PowerShell gets filename from the path

In the script, the $filePath variable stores the full path to the file. We use the Split-Path with the -Leaf parameter to extract the filename from the $filePath and store it in the $fileName variable.

Finally, we use the Write-Output cmdlet to display the extracted filename.

This script will extract and display the filename “my_log.txt” from the specified file path.

Conclusion

I hope the above article on extracting the filename from a path in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.