Two ways of skinning a cat.
If you need to parse a filename to separate the main body of the filename from the extension.
#1 The first way is useful if you have the file as a .NET object, here is an example that makes everything obvious:
$FileObject = Get-ChildItem "MyFileName.txt"
Write-Host "Main body is: $($FileObject.BaseName)"
Write-Host "File Extension is: $($FileObject.Extension)"
#2 If you only have the filename as a string, you can do this:
$StringOfFileName = "MyFileName.txt"
Write-Host "Main body is: $([System.IO.Path]::GetFileNameWithoutExtension($StringOfFileName))"
Write-Host "Main body is: $([System.IO.Path]::GetExtension($StringOfFileName))"
Ironically the former where you have a .NET object is pure PowerShell and the latter where you do not have a .NET object is a .NET call.
Post a Comment