powershell - extract file name and extension

culter picture culter · Mar 20, 2012 · Viewed 224.4k times · Source

I need to extract file name and extension from e.g. my.file.xlsx. I don't know the name of file or extension and there may be more dots in the name, so I need to search the string from the right and when I find first dot (or last from the left), extract the part on the right side and the part on the left side from that dot.

Maybe there is better solution, but I did'n find anything here or anywhere else. Thank you

Answer

Goyuix picture Goyuix · Mar 20, 2012

If the file is coming off the disk and as others have stated, use the BaseName and Extension properties:

PS C:\> dir *.xlsx | select BaseName,Extension

BaseName                                Extension
--------                                ---------
StackOverflow.com Test Config           .xlsx  

If you are given the file name as part of string (say coming from a text file), I would use the GetFileNameWithoutExtension and GetExtension static methods from the System.IO.Path class:

PS C:\> [System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
Test Config
PS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx")
.xlsx