powershell - extract file name and extension

前端 未结 9 890
温柔的废话
温柔的废话 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:43

    If is from a text file and and presuming name file are surrounded by white spaces this is a way:

    $a = get-content c:\myfile.txt
    
    $b = $a | select-string -pattern "\s.+\..{3,4}\s" | select -ExpandProperty matches | select -ExpandProperty value
    
    $b | % {"File name:{0} - Extension:{1}" -f $_.substring(0, $_.lastindexof('.')) , $_.substring($_.lastindexof('.'), ($_.length - $_.lastindexof('.'))) }
    

    If is a file you can use something like this based on your needs:

    $a = dir .\my.file.xlsx # or $a = get-item c:\my.file.xlsx 
    
    $a
        Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps
    
    
    Mode           LastWriteTime       Length Name
    ----           -------------       ------ ----
    -a---      25/01/10    11.51          624 my.file.xlsx
    
    
    $a.BaseName
    my.file
    $a.Extension
    .xlsx
    

提交回复
热议问题