While working with files in the Windows Operating system, often we have a requirement to get a filename without extension. Using PowerShell, it’s easy to get the filename using the Microsoft .Net class library and methods.
Systen.IO.Path
.net class has the GetFileNameWithoutExtension() method to get a filename without extension. The GetFileNameWithoutExtension (string path) method accepts the string path as a parameter and returns the filename without extension.
In this article, I will explain how to use PowerShell to get filename without extension using the .net class System.IO.Path
library with examples.
PowerShell Get FileName Without Extension
If you want to get filename without extension in PowerShell, use the System.IO.Path GetFileNameWithoutExtension() method.
Let’s consider an example, if you want to get filename located at D:\LogTest\Newline-FileTest.txt, use the below command
[System.IO.Path]::GetFileNameWithoutExtension('D:\LogTest\Newline-FileTest.txt')
In the above PowerShell script, GetFileNameWithoutExtension()
the method accepts the file path and gets the file name without extension.
[System.IO.Path]::GetFileNameWithoutExtension('D:\LogTest\Newline-FileTest.txt')
Newline-FileTest
result of the above script is Newline-FileTest without .txt extension.
Note: Check if the file exists in PowerShell before you use the above script to get the file name!
Cool Tip: How to get file extension in PowerShell!
PowerShell Get Multiple File Names Without Extension
If you want to get multiple file names without extension in the given directory, use the PowerShell Get-ChildItem cmdlet to get items in one or more specified location pipes to GetFileNameWithoutExtension() to get a filename without extension in the below script.
Get-ChildItem -Path D:\PowerShell\ -Filter *.csv | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}
In the above PowerShell script, the Get-ChildItem cmdlet gets files from a specified path, uses a filter to get the .csv file extension, and passes the output to the second command.
The second command uses the ForEach-Object
to iterate over files and uses System.IO.Path
class GetFileNameWithoutExtension() method to get file name without extension.
The output of the above command to get multiple filename without extension as below
Cool Tip: How to get file creation date in PowerShell!
Conclusion
In the above article, we learned how to get file name without extension using the System.IO.Path .net class library.
The GetFileNameWithoutExtension() method is used to get file name without extension for a given file path or get multiple filename without extension in a specified folder or current directory.
Read more here on how to count lines in files and words in files using PowerShell.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.