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.
[System.IO.Path]::GetDirectoryName("c:\temp\abc\myproj1\newdata.txt")
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
Split-Path "c:\temp\abc\myproj1\newdata.txt"
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
Comments on this entry are closed.
Hello , I have a problem to be solved . I have to get the directory of unzip file inside it there is xml file that contain credential info . Do you know how?
Late response, but if you still have the requirement, then try http://techibee.com/powershell/reading-zip-file-contents-without-extraction-using-powershell/2152
If the folder was named c:\temp\abc\scripts\myproj1\textfiles\newdata.txt, and I wanted to return only the “textfiles” folder name, how would that be scripted in PowerShell?
You can do it this way.
PS C:\> $filepath = “c:\temp\abc\scripts\myproj1\textfiles\newdata.txt”
PS C:\> $dirpath = [System.IO.Path]::GetDirectoryName($filepath)
PS C:\> $dirname = [System.IO.Path]::GetFileName($dirpath)
PS C:\> Write-Host $dirname
textfiles
PS C:\>
Thank You!!!!
You could run the following to get the folder name of the current directory:
“`
[System.IO.Path]::GetFileName($(Get-Location))
“`