«

»

Mar 25

Powershell Tips of the week #3 – Find parent folder

How to find the parent folder of a path that is stored in a variable

For the purpose of the example I will manually add a path to a variable.

$VarA = "\\Domain.net\dfs\files\dan.fortier\"

The parent folder of this path is “\\Domain.net\dfs\files” but lets find it with powershell using the Get-Item cmdlet.

$ParentFolder = (Get-Item $VarA).parent.FullName
Write-host $ParentFolder

Result:
\\Domain.net\dfs\files

If you want to get to one level higher, add another .parent:

$ParentFolder = (Get-Item $VarA).parent.parent.FullName
Write-host $ParentFolder

Result:
\\Domain.net\dfs\

Note that the path need to be valid, otherwise you will get an error.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>