When searching, I was surprised that there were only answers for getting filename without extension but they discard path whereas I want to keep the path :
So is there a standard method for that or do I need to parse myself ?
Note:
This answer shows a solution for modifying a given path string.
If you're dealing with System.IO.FileInfo
instances as input, such as output by Get-ChildItem
, consider the solution in Daniel's answer.
It is not the most obvious solution, but it is concise, based on the [System.IO.Path]::ChangeExtension()
method:
PS> [IO.Path]::ChangeExtension('C:\path\to\some\file.txt', [NullString]::Value)
C:\path\to\some\file
What makes the solution obscure is the need to pass [NullString]:Value
in order to pass a true null
value to the .NET method - using $null
does not work, because PowerShell treats it like ""
, i.e. the empty string,[1] which causes the method to keep the .
part of the extension.
The slightly less obscure, but more verbose alternative is to trim the trailing .
after the fact:
PS> [IO.Path]::ChangeExtension('C:\path\to\some\file.txt', '').TrimEnd('.')
C:\path\to\some\file
[1] By design, PowerShell doesn't let you store $null
in string-typed variables, which means that a [string]
-typed parameter variable contains the empty string by default and even passing or assigning $null
is converted to the empty string. The [NullString]::Value
singleton was introduced in v3 specifically to allow passing true null
values to .NET APIs with string
-typed parameters.