In this post, you will see various options for extracting folder name from given file or directory path. This is generally useful in many ways as you work more with file and folders.
Let us proceed to see how we can achieve this. For example you have a absolute path c:\temp\abc\myproj1\newdata.txt file and you want to get the parent directory of the newdata.txt from the path string that is given to you. This operation might look simple if you just have one path and what you do if you have to do this for some 10,000 files paths? Obviously a programmatic approach is destination.
My favorite approach is using [System.IO.Path] Class.
The GetDirectoryName method takes a path as input and returns the directory name. Alternative to this is using split-path cmdlet that comes with PowerShell. Using this cmdlet is much better than GetDirectoryName method because this cmdlet provides several other features.
What they are?
Like the GetDirectoryName method, it also returns the parent directory
It verifies if the path exists or not when -Resolve parameter is specified
Split-Path "c:\temp\abc\myproj1\newdata.txt" -Resolve
It can be used to get the file name from path instead of parent directory.
Split-Path "c:\temp\abc\myproj1\newdata.txt" -Leaf
Hope this tip helps you