Public/Remove-GitWorktree.ps1

<#
.SYNOPSIS
    Removes a git worktree and deletes its associated branch.
.DESCRIPTION
    Removes the worktree at -Path (must be a registered git worktree),
    then deletes the branch that was checked out there. Use -Force to
    skip the dirty-state check.
.EXAMPLE
    Remove-GitWorktree -Path C:\repos\myrepo\feature\my-feature
.EXAMPLE
    Remove-GitWorktree -Path C:\repos\myrepo\hotfix\1.0.1 -Force
#>

function Remove-GitWorktree {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias('FullName')]
        [string] $Path,

        [Parameter()]
        [switch] $Force,

        [Parameter()]
        [string] $RepoPath
    )

    process {
        $Path = (Resolve-Path $Path -ErrorAction Stop).Path

        # Find the bare repo root — either supplied or derived from Path
        if ($RepoPath) {
            $root = (Resolve-Path $RepoPath -ErrorAction Stop).Path
        }
        else {
            $root = Get-GitRoot -Path $Path
        }

        # Get worktree list and find matching entry
        $worktrees = Get-WorktreeList -RepoPath $root
        $entry     = $worktrees | Where-Object { $_.Path -eq $Path }

        if (-not $entry) {
            throw "Path '$Path' is not a registered worktree of '$root'"
        }

        if ($entry.IsBare) {
            throw "Cannot remove the bare repo worktree entry itself."
        }

        $branch = $entry.Branch

        # Dirty-state check
        if (-not $Force) {
            $status = git -C $Path status --porcelain 2>$null
            if ($status) {
                Write-Warning "Worktree '$Path' has uncommitted changes:"
                $status | ForEach-Object { Write-Warning " $_" }
                throw "Aborting removal of dirty worktree. Use -Force to override."
            }
        }

        if ($PSCmdlet.ShouldProcess($Path, "Remove worktree and delete branch '$branch'")) {
            Write-Verbose "Removing worktree: $Path"
            if ($Force) {
                git -C $root worktree remove --force $Path
            }
            else {
                git -C $root worktree remove $Path
            }
            if ($LASTEXITCODE -ne 0) { throw "git worktree remove failed for '$Path'" }

            if ($branch) {
                Write-Verbose "Deleting branch: $branch"
                git -C $root branch -D $branch
                if ($LASTEXITCODE -ne 0) {
                    Write-Warning "Worktree removed but could not delete branch '$branch'"
                }
            }

            Write-Host "Removed worktree : $Path" -ForegroundColor Yellow
            if ($branch) { Write-Host "Deleted branch : $branch" -ForegroundColor Yellow }
        }
    }
}