I have an absolute path in a variable in my powershell 2.0 script. I want to strip off the extension but keep the full path and file name. Easiest way to do that?
So
# the path
$file = 'C:\Temp\MyFolder\mytextfile.fake.ext.txt'
# using regular expression
$file -replace '\.[^.\\/]+$'
# or using System.IO.Path (too verbose but useful to know)
Join-Path ([System.IO.Path]::GetDirectoryName($file)) ([System.IO.Path]::GetFileNameWithoutExtension($file))
if is a [string]
type:
$file.Substring(0, $file.LastIndexOf('.'))
if is a [system.io.fileinfo]
type:
join-path $File.DirectoryName $file.BaseName
or you can cast it:
join-path ([system.io.fileinfo]$File).DirectoryName ([system.io.fileinfo]$file).BaseName
You should use the simple .NET framework method, instead of cobbling together path parts or doing replacements.
PS> [System.IO.Path]::GetFileNameWithoutExtension($file)
https://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension%28v=vs.110%29.aspx
Here is the best way I prefer AND other examples:
$FileNamePath
(Get-Item $FileNamePath ).Extension
(Get-Item $FileNamePath ).Basename
(Get-Item $FileNamePath ).Name
(Get-Item $FileNamePath ).DirectoryName
(Get-Item $FileNamePath ).FullName
Regardless of whether $file
is string
or FileInfo
object:
(Get-Item $file).BaseName