≡ Menu

Powershell: Get parent directory name from file or directory path

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

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.

  • Ahmad yamout April 26, 2017, 11:52 am

    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?

  • Richard May 11, 2018, 6:40 pm

    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?

    • Wintel Rocks May 29, 2018, 6:02 pm

      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
      PS C:\>

      • Adam M Losee July 20, 2018, 8:55 am

        Thank You!!!!

        • Himujjal August 8, 2020, 12:48 am

          You could run the following to get the folder name of the current directory: