Private/Open-WorktreeSolution.ps1

<#
.SYNOPSIS
    Finds and opens a .sln or .slnx file inside a worktree directory.
.DESCRIPTION
    Searches up to 3 directory levels deep for solution files. Opens immediately
    if exactly one is found. Prompts the user to pick when multiple are found.
    Does nothing if none are found.
#>

function Open-WorktreeSolution {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string] $WorktreePath
    )

    $solutions = @(
        Get-ChildItem -Path $WorktreePath -Include '*.sln', '*.slnx' `
            -Recurse -Depth 3 -ErrorAction SilentlyContinue
    )

    if ($solutions.Count -eq 0) { return }

    $selected = if ($solutions.Count -eq 1) {
        $solutions[0]
    }
    else {
        Write-Host 'Multiple solution files found:' -ForegroundColor Yellow
        for ($i = 0; $i -lt $solutions.Count; $i++) {
            Write-Host " [$i] $($solutions[$i].Name)" -ForegroundColor Yellow
        }
        do {
            $raw   = Read-Host "Select solution (0-$($solutions.Count - 1))"
            $idx   = $null
            $valid = [int]::TryParse($raw, [ref]$idx) -and $idx -ge 0 -and $idx -lt $solutions.Count
            if (-not $valid) {
                Write-Warning "Invalid selection — enter a number between 0 and $($solutions.Count - 1)."
            }
        } while (-not $valid)
        $solutions[$idx]
    }

    Write-Host "Opening solution : $($selected.FullName)" -ForegroundColor Cyan
    Start-Process $selected.FullName
}