Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 625
Mark Allison Avatar asked Feb 08 '13 10:02

Mark Allison


People also ask

How do I find a file without an extension?

Windows Explorer - Advanced Query Syntax You can use a for /f loop iterating the output of a dir command with the /B and /A-D parameters, and then use some conditional if logic to only output files without any extensions using substitutions for the iterated files in the specified directory.

How do I get the file path in PowerShell?

Use Select-Object to Get Full Path of the File Use the Get-ChildItem cmdlet in PowerShell to get the files in the folder using the file filter and using the Select-Object cmdlet to get the full path of the file using ExpandProperty FullName.

How do I copy a file without an extension in PowerShell?

In Powershell you can use Copy-Item to copy a file and you can specify the sources and the targets fullname either with or without extension. In an open cmd window, type: for %A in (file. mov) do echo %~dpnA - %~xA - %~zA.


2 Answers

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

like image 128
Antebios Avatar answered Sep 25 '22 02:09

Antebios


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
like image 39
CB. Avatar answered Sep 22 '22 02:09

CB.