Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing path and extension from filename in PowerShell

Tags:

powershell

People also ask

How do I get just the filename in PowerShell?

Use the GetFileName Method to Extract the Filename From a Path in PowerShell. The GetFileName method of the . NET's Path class returns the file name and extension of the specified path.

How do I change a file extension in PowerShell?

Change file extensions with PowerShell You can also use the Rename-Item to change file extensions. If you want to change the extensions of multiple files at once, use the Rename-Item cmdlet with the Get-ChildItem cmdlet.

How do I get the file extension in PowerShell?

Use the Get-ChildItem cmdlet to get the file item and using its Extension property it returns the file name extension. The Get-ChildItem command accepts the file path as input and gets the file item. It then passes the output to the Select command to get file extension using the Extension property.


There's a handy .NET method for that:

C:\PS> [io.path]::GetFileNameWithoutExtension("c:\temp\myfile.txt")
myfile

Way easier than I thought to address the issue of displaying the full path, directory, file name or file extension.

$PSCommandPath
(Get-Item $PSCommandPath ).Extension
(Get-Item $PSCommandPath ).Basename
(Get-Item $PSCommandPath ).Name
(Get-Item $PSCommandPath ).DirectoryName
(Get-Item $PSCommandPath ).FullName
$ConfigINI = (Get-Item $PSCommandPath ).DirectoryName+"\"+(Get-Item $PSCommandPath ).BaseName+".ini"
$ConfigINI

other forms:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
split-path -parent $PSCommandPath
Split-Path $script:MyInvocation.MyCommand.Path
split-path -parent $MyInvocation.MyCommand.Definition
[io.path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)

Inspired by an answer of @walid2mi:

(Get-Item 'c:\temp\myfile.txt').Basename

Please note: this only works if the given file really exists.


or

([io.fileinfo]"c:\temp\myfile.txt").basename

or

"c:\temp\myfile.txt".split('\.')[-2]

you can use basename property

PS II> ls *.ps1 | select basename