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,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
just do it:
$file=Get-Item "C:\temp\file.htm"
$file.Basename
$file.Extension