It is a very common requirement to have just file name extracted from full path while working on your PowerShell scripts. For example, your script received a file full path(c:\abc\xyz\test.txt) and you want to just get the file name from it with or without extension(ex: test or test.txt). In this post how to achieve this.
There are several ways to do this. For example, a programmer with good regex knowledge tend to write a regex to extract the file name. Or you can also use Split-Path cmdlet in PowerShell do this. The approach I am going to share here is based on .Net classes and my favourite approach. I am not against using cmdlets but thing is they also internally use the .Net classes. So why not use them directly?
Get File name from full path.
[System.IO.Path]::GetFileName("C:\abc\xyz\test.txt")

Get File name with extension from full path
[System.IO.Path]::GetFileNameWithoutExtension("C:\abc\xyz\test.txt")

As you can see I am using System.IO.Path classes to perform this work. You can explore the other methods available in these modules and there are many useful functions.
Thank you!! I had been trying to figure this out last weekend and I think this is the answer!
I was trying to write something that would search for file extensions and move their corresponding folders to a new location but I couldn’t get the path object. It would move the files but not the folder. Do you have any examples of how I should do that?
Thanks!
You might want to check this..
https://serverfault.com/questions/194827/writing-a-powershell-script-to-copy-files-with-certain-extension-from-one-folder
Is this like a command in cmd?
Hi,
You need to run from a PowerShell window or a PS script.