Remove Path and Extension From Filename in PowerShell

Rohan Timalsina Jan 30, 2023 Apr 01, 2022
  1. Use BaseName Property to Remove Path and Extension From Filename in PowerShell
  2. Use .NET Class to Remove Path and Extension From Filename in PowerShell
Remove Path and Extension From Filename in PowerShell

PowerShell supports the handling of various file operations in the system. You can perform tasks like create, copy, move, rename, edit, delete, and view files in PowerShell.

There are different cmdlets in PowerShell that you can use to get the name full path and extension of a file. While working with files in the system, you might need to get the file name without path and extension.

This tutorial will teach you to remove path and extension from filename in PowerShell.

Use BaseName Property to Remove Path and Extension From Filename in PowerShell

The cmdlet Get-Item gets the item at the specified location. It displays the Directory, Mode, LastWriteTime, Length, and Name of a specified file.

Command:

Get-Item test.txt

Output:

Directory: C:\Users\rhntm

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         3/12/2022   7:36 PM             70 test.txt

You can use the BaseName property with Get-Item to get only the file name with the Get-Item.

(Get-Item test.txt).BaseName

Output:

test

If you want to remove path and extension in multiple files, you can use the Get-ChildItem cmdlet. The following command shows how to get multiple file names without path and extension in PowerShell.

Command:

(Get-ChildItem "C:\Users\rhntm\*.txt").BaseName

Output:

hello
new
record
test

The command above gets all .txt files name in the directory C:\Users\rhtnm.

Use .NET Class to Remove Path and Extension From Filename in PowerShell

The following method uses the .NET framework class to remove the path and extension from the file name. The System.IO.Path .NET class has the GetFileNameWithoutExtension() method which gets the filename without extension in PowerShell.

You can run the command below if you want to get the file name located at C:\Users\rhntm\test.txt.

Command:

[System.IO.Path]::GetFileNameWithoutExtension("C:\Users\rhntm\test.txt")

Output:

test

You can also use the System.IO.FileInfo class with the basename property to get the file name without the extension.

Command:

([System.IO.FileInfo]"C:\Users\rhntm\test.txt").BaseName

Output:

test

This article has covered different methods to get the file name without path and extension in PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell File