Search code examples
.netpowershellpowershell-2.0

powershell - extract file name and extension


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.

How?


Solution

  • 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