1

I have a path, such as D:\repos\my-repo\some\script\path.ps1, and I want to get the path just up to the repo name: D:\repos\my-repo. What's the best way to accomplish this? Here's what I've got right now:

$fullPath = $MyInvocation.MyCommand.Path # D:\repos\my-repo\some\script\path.ps1
"{0}my-repo" -f [regex]::Split($fullPath, 'my-repo')[0]

This works but it's pretty ugly and inefficient in my opinion. Is there a better way to accomplish this?

jerdub1993
  • 355
  • 1
  • 8
  • If you're trying to find the root of a git repository, you can get that from git directly: https://stackoverflow.com/a/957978/5747548 – jkiiski Mar 04 '23 at 05:47

2 Answers2

1

Don't see what's inefficient about what you currently have but here are 2 different ways you could accomplish the same.

$path = 'D:\repos\my-repo\some\script\path.ps1'
$path -replace '(?<=my-repo)\\.*'

Details on: https://regex101.com/r/ZkdlCR/1

$path = 'D:\repos\my-repo\some\script\path.ps1'
$path -replace '(?:\\[^\\]*){3}$'

Details on: https://regex101.com/r/6gk4MF/1

If you were looking for the object oriented approach you could also cast FileInfo to your path and then get the parent directory of the file (.Directory) and from there you can use the .Parent property to traverse it.

$path = 'D:\repos\my-repo\some\script\path.ps1'
([System.IO.FileInfo] $path).Directory.Parent.Parent.FullName
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • I guess I was hoping there would be a .NET method that can accomplish it without regex. Something like `[System.IO.Path]::GetSpecificDirectoryPath('D:\repos\my-repo\some\script\path.ps1', 'my-repo')`. Worst comes to worst, your first option works great so I'll go with that. – jerdub1993 Mar 04 '23 at 04:23
  • 1
    @jerdub1993 I added the .NET way you could do it. Path API doesnt offer a way to get specifically what you're looking for in this case – Santiago Squarzon Mar 04 '23 at 04:31
  • Unfortunately the path is variable, so no way of knowing how many "`.Parent`s" are needed to get to the repo directory. I'll go with the regex method. – jerdub1993 Mar 04 '23 at 04:36
  • @jerdub1993 yep, has the same problem as the 2nd regex and why I put the lookbehind method as first since its the more robust way to get it. – Santiago Squarzon Mar 04 '23 at 04:39
1

Another regex solution:

$path = 'D:\repos\my-repo\some\script\path.ps1'
($path -split '(?<=\\my-repo)\\')[0]
  • Output:
PS > $path = 'D:\repos\my-repo\some\script\path.ps1'
PS >
PS > ($path -split '(?<=\\my-repo)\\')[0]
D:\repos\my-repo
PS >
PS > $path = 'D:\repos\anotehrLevel\my-repo\some\script\path.ps1'
PS >
PS > ($path -split '(?<=\\my-repo)\\')[0]
D:\repos\anotehrLevel\my-repo
Keith Miller
  • 702
  • 5
  • 13