Search code examples
powershell

How do I get a file path without extension in PowerShell?


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


Solution

  • 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