Home > Software design >  How do I change directory to a specific folder in a path?
How do I change directory to a specific folder in a path?

Time:11-18

I need to check if my current location contains a directory called _framework and if it does, set the location to that folder.

The Problem is, I don't know what's in the path before my keyword, or after my keyword.

So to visualize, basically if I am here:

C:\foo\bar\some\_framework\stuff\xy

I need to jump here:

C:\foo\bar\some\_framework

I've written a code that works:

$CurrentPath = (Get-Location).Path
$SplitUp = $CurrentPath -split '\\'
$Result = @()
foreach ($Split in $SplitUp) {
    $Result  = $Split
    if ($Split -eq '_framework') { break }
}
Set-Location ($Result -join '\')

but I find it massivelly ugly. is there a simple cmdlet that would give me my desired result in an easier way, without splitting and iterating the result - or ist this the only solution?

It has to be available in PowerShell 5.1

CodePudding user response:

Use a single regex -replace operation to remove anything after the \_framework\ part:

$currentPath = "$PWD"

if($currentPath -like '*\_framework\*'){
  $frameworkPath = $currentPath -replace '(?<=\\_framework)\\.*'
  Set-Location -LiteralPath $frameworkPath
} else {
  throw 'not a valid path'
}

Alternatively, create a small utility function to resolve the correct parent for you (you can replace my implementation below with your own if you so feel):

function Get-AncestralPathByName
{
  param(
    [string]$Name
  )

  $path = "$PWD"

  while($path -and $path -notmatch "\\$([regex]::Escape($Name))\\?$"){
    $path = Split-Path $path
  }

  return $path
}

Now the code at the callsite becomes super simple:

if($targetPath = Get-AncestralPathByName -Name '_framework'){
  Set-Location $targetPath
} else {
  throw 'could not resolve target path'
}
  • Related