powershell - extract file name and extension powershell - extract file name and extension powershell powershell

powershell - extract file name and extension


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,ExtensionBaseName                                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 ConfigPS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx").xlsx


PS C:\Windows\System32\WindowsPowerShell\v1.0>split-path "H:\Documents\devops\tp-mkt-SPD-38.4.10.msi" -leaftp-mkt-SPD-38.4.10.msiPS C:\Windows\System32\WindowsPowerShell\v1.0> $psversiontableName                           Value----                           -----CLRVersion                     2.0.50727.5477BuildVersion                   6.1.7601.17514PSVersion                      2.0WSManStackVersion              2.0PSCompatibleVersions           {1.0, 2.0}SerializationVersion           1.1.0.1PSRemotingProtocolVersion      2.1


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:\psMode           LastWriteTime       Length Name----           -------------       ------ -----a---      25/01/10    11.51          624 my.file.xlsx$a.BaseNamemy.file$a.Extension.xlsx