Get Filename without Extension in PowerShell

💡 Quick Answer

You can get filename without extension in PowerShell using BaseName property with Get-Item cmdlet.

Output:

While working on a Windows operating system, you may often encounter the requirement of getting filename without extension.

For example:

FileName : C:\temp\sample.txt
FileName without extension: sample

In this post, we will see various ways to get FileName without extension in PowerShell.

Get FileName without extension for single file

Using BaseName property with Get-Item cmdlet

To get filename without extension in powershell, you can use Get-Item cmdlet to get item at specified location and then use BaseName attribute to get filename without extension.

Output:

Here, Get-Item cmdlet is use to get item at specified location. This displays Name, Length, Mode, LastWriteTime and Directory of a particular file.

Here the command will be;

Output:

BaseName property along with the Get-Item helps you to get filename without extension.

If file does not exist, then you will get error as below:

Output:

Using System.IO.Path ‘s GetFileNameWithoutExtension() method

To remove extension from the filename, you can use System.IO.Path ‘s GetFileNameWithoutExtension() method. In this method, you will get the filename without extension in your PowerShell.

For that, run the following command to get your file name location at C:\User\rhtnm\test.txt.

Output:

If file doesn’t exist, you won’t get error in this method.

Get FileName without extension for multiple files

If you are looking to get your filename without extension in the case of your multiple files, use Get-ChildItem cmdlet with GetFileNameWithoutExtension() in PowerShell.

Here is PowerShell command to get FileName without extension for multiple files

Output:

In above PowerShell script, Get-ChildItem as cmdlet help you get specified path files while using a filter for getting .txt extension. Then the output is passed to the second command.

Second command uses ForEach-Object to iterate over list of files and uses System.IO.Path’s GetFileNameWithoutExtension() method on each file to get filename without extension.

Conclusion

Removing a filename without extension is easier than ever before. We discussed the BaseName property with Get-Itemcmdlet, .Net Class System.IO.Path‘s GetFileNameWithoutExtension() method. We have also discussed how to get filename without extension for multiple files. You can apply these frameworks in an efficient way and get your filename without extension.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *