In Powershell v6, the split-path has the -Extension
parameter to access the extension of a file name, for example:
$pathToResume = "R:\Work\cover.letter_resume_base.odt"
$extension = Split-Path -Extension $pathtoResume
Write-Output $extension # Will print .odt
However, Powershell 3 doesn't provide the -Extension
parameter, but I came up with this solution:
# Notice the period between cover and letter
$pathToResume = "R:\Work\cover.letter_resume_base.odt"
$pathToResumeLeaf = Split-Path -Leaf $pathToResume
$pathToResumeLeafArray = $pathToResumeLeaf.Split(".")
$fileExtension = $pathToResumeLeafArray | Select-Object -Last 1
Write-Output $fileExtension # Will print odt
I still get the file extension, but without the period. No matter how many periods are in the filename or the length of the array, I will get the same output.
I can't think of any situation where the period is required. If I wanted to print the period with the extension, I can easily add it when I use Write-Output
or [string]::format()
Is Select-Object
as I've shown above a viable solution when -Extension
is unavailable?