Get FileName with or without extension from full path using PowerShell

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:abcxyztest.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:abcxyztest.txt")

Get File name with extension from full path

[System.IO.Path]::GetFileNameWithoutExtension("C:abcxyztest.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.

稿源:Techibee.com (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » Get FileName with or without extension from full path using PowerShell

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录