devfunkd
devfunkd

Reputation: 3234

Powershell climb directory tree backwards

I have script located in C:\projects\bacon\packages\build\run.ps1 and I am trying to locate the solution folder (in this case bacon). Everything I've found shows how to climb forward if you know the folder name. But I don't know the project name, so I need to climb backwards until I find the first containing folder that has a packages or dependencies folder within the given script's path.

The closest function I've found is to use Split-Path $script:MyInvocation.MyCommand.Path to get my script's path and perhaps loop backwards somehow? but I can't find anyway of looping the folders backwards until I find the "packages" or "dependencies" folder.

Upvotes: 2

Views: 939

Answers (1)

Joseph Alcorn
Joseph Alcorn

Reputation: 2442

You can use a combination of Get-Item and Get-ChildItem. Get-Item returns an object that has a Parent property. You can limit Get-ChildItem to just directory objects. You can then use this to trek backwards:

$current = Get-Item .
Write-Host $Current.Parent
do
{
    $parent = Get-Item $current.Parent.FullName
    $childDirectories = $parent | Get-ChildItem -Directory | ? { $_.Name -in @("dependencies","packages") }
    $current = $parent
} until ($childDirectories)
$bacon = $parent.FullName

I should say that the first line $current = Get-Item . will only work as is if the current path for the PowerShell runspace is at the end of the tree you are working with.

In your script, if you are using v3, you can replace the . with $PSScriptRoot.

Upvotes: 1

Related Questions