Reputation: 7228
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 if I have C:\Temp\MyFolder\mytextfile.fake.ext.txt
in a variable called, say $file
I want to return
C:\Temp\MyFolder\mytextfile.fake.ext
Upvotes: 18
Views: 39468
Reputation: 375
Here is another solution using the .NET api, Path.ChangeExtension
:
[System.IO.Path]::ChangeExtension($file, [NullString]::Value)
The second parameter must be explicitly specified as [NullString]::Value
, since $null
will be regarded as [String]::Empty
(""
) [1], which will leave an unwanted "."
as the end.
PS> [System.IO.Path]::ChangeExtension("C:\Temp\MyFolder\mytextfile.fake.ext.txt",[NullString]::Value)
C:\Temp\MyFolder\mytextfile.fake.ext
PS> [System.IO.Path]::ChangeExtension("C:\Temp\MyFolder\mytextfile.fake.ext.txt",$null)
C:\Temp\MyFolder\mytextfile.fake.ext.
[1] PowerShell/PowerShell #4616
Upvotes: 0
Reputation: 1781
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
Using these commands, the full path stripped by the extension is obtained as follows
$name = (Get-Item $file).Basename
$dir = (Get-Item $file).DirectoryName
$nameNoExt = "$dir\$name"
Upvotes: 24
Reputation: 1082
Regardless of whether $file
is string
or FileInfo
object:
(Get-Item $file).BaseName
Upvotes: 3
Reputation: 22414
You should use the simple .NET framework method, instead of cobbling together path parts or doing replacements.
PS> [System.IO.Path]::GetFileNameWithoutExtension($file)
Upvotes: 5
Reputation: 42083
# 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))
Upvotes: 6
Reputation: 60976
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
Upvotes: 31