How to Get the Parent's Parent Directory in PowerShell

Rohan Timalsina Feb 16, 2024
  1. Use Split-Path Cmdlet to Get the Parent’s Parent Directory in PowerShell
  2. Use Parent Property to Get the Parent’s Parent Directory in PowerShell
How to Get the Parent's Parent Directory in PowerShell

The path defines the location of files and directories on the computer. There are several cmdlets to get the path of files and directories in PowerShell.

This tutorial will teach you to get the parent’s parent directory of a path using PowerShell.

Use Split-Path Cmdlet to Get the Parent’s Parent Directory in PowerShell

The Split-Path cmdlet displays the specified part of a path. It can be a parent folder, subfolder, file name, or file extension.

The default is to return the parent folder of the specified path.

The following command returns the parent folder of a path C:\New\complex\formula.png.

Split-Path 'C:\New\complex\formula.png'

Output:

C:\New\complex

The following example gets the parent’s parent folder of a path C:\New\complex\formula.png.

Split-Path (Split-Path 'C:\New\complex\formula.png')

Output:

C:\New

You can also pipe a path string to Split-Path and get the specific part. This command also prints the parent’s parent directory of a path C:\New\complex\formula.png.

'C:\New\complex\formula.png' | Split-Path | Split-Path

Output:

C:\New

For more information, see Split-Path.

Use Parent Property to Get the Parent’s Parent Directory in PowerShell

Get-Item is another cmdlet you can use to get the parent directory in PowerShell. This method works best on the directory path.

The DirectoryInfo object in PowerShell has a Parent property, which denotes the parent directory’s path.

The following command returns the parent directory of a path C:\New\complex.

(Get-Item 'C:\New\complex').Parent.FullName

Output:

C:\New

You can use the below command to get the parent’s parent directory of a path C:\New\complex.

(Get-Item 'C:\New\complex').Parent.Parent.FullName

Output:

C:\
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Directory