PowerTip: Use PowerShell to Find Grandparent of Path

Summary: Use Windows PowerShell to easily find the grandparent of a path.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find a directory that is two levels up in a nested path?

Hey, Scripting Guy! Answer Use the Split-Path cmdlet and pipe the results to Split-Path. In the following example,
          the path to a Windows PowerShell module is split, and then the parent of that path is split again:

(get-module -l)[0].Path | split-path -Parent | Split-Path -Parent

Comments (1)

  1. James Brown says:

    I see that one can add ‘split-path -parent’ as many times as necessary until you reach the root. I’ll have to think of a way to determine how many levels exist in a path (search for the number of backslashes?), and then repeat ‘split-path -parent’ ‘x’ number of times until you’ve reached root.

Skip to main content