powershell - extract file name and extension

前端 未结 9 924
温柔的废话
温柔的废话 2020-12-24 04:09

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

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 04:39

    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
    

提交回复
热议问题