Public/Remove-DevVmPersistentPath.ps1

<#
.SYNOPSIS
Remove a runtime from the user's persistent PATH environment variable.
 
.DESCRIPTION
Remove-DevVmPersistentPath removes the specified runtime from the user's PATH environment variable.
This removes the runtime from all future terminal sessions.
 
The function:
- Removes all PATH entries matching the runtime's base path
- Requires no administrator privileges (modifies user-level PATH only)
- Updates both the persistent PATH and the current session PATH
 
.PARAMETER Runtime
The name of the runtime (e.g., 'node', 'java', 'maven').
 
.PARAMETER BasePath
The base installation path for the runtime.
 
.EXAMPLE
Remove-DevVmPersistentPath -Runtime node -BasePath C:\node
 
Removes all Node.js entries from the user's persistent PATH.
 
.EXAMPLE
Remove-DevVmPersistentPath -Runtime java -BasePath C:\java
 
Removes all Java entries from the user's persistent PATH.
 
.NOTES
This function modifies the user-level PATH environment variable. The changes will take effect
in new terminal sessions. The current session is also updated immediately.
#>

function Remove-DevVmPersistentPath {
    [CmdletBinding(SupportsShouldProcess = $true)]
    [OutputType([System.Boolean])]
    param(
        [Parameter(Mandatory)]
        [string]$Runtime,

        [Parameter(Mandatory)]
        [string]$BasePath
    )

    if (-not $PSCmdlet.ShouldProcess("User PATH", "Remove persistent PATH for $Runtime")) {
        return $false
    }

    try {
        # Get current user PATH
        $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
        $pathArray = @($userPath -split ';' | Where-Object { $_ })

        # Remove paths for this runtime
        $baseLower = $BasePath.ToLower()
        $cleanedArray = @($pathArray | Where-Object {
            $_.ToLower() -notlike "$baseLower*"
        })

        # Update if changed
        if ($cleanedArray.Count -ne $pathArray.Count) {
            $newPath = $cleanedArray -join ';'
            [Environment]::SetEnvironmentVariable('Path', $newPath, 'User')

            Write-Information "Runtime removed from persistent PATH: $Runtime" -InformationAction Continue

            # Update current session
            $env:Path = $newPath + ';' + [Environment]::GetEnvironmentVariable('Path', 'Machine')

            return $true
        }

        Write-Information "$Runtime was not in persistent PATH" -InformationAction Continue
        return $false
    }
    catch {
        Write-Error "Failed to remove from PATH: $_"
        return $false
    }
}