function nvm {
if ($args[0] -eq 'use' -and $args.Count -eq 1) {
$nvmrcPath = Join-Path (Get-Location) '.nvmrc'
if (-not (Test-Path $nvmrcPath)) {
Write-Host "No .nvmrc found in current directory." -ForegroundColor Red
return
}
$requestedVersion = (Get-Content $nvmrcPath -Raw).Trim().TrimStart('v')
if ([string]::IsNullOrWhiteSpace($requestedVersion)) {
Write-Host ".nvmrc is empty." -ForegroundColor Red
return
}
$installedVersions = & nvm.exe list 2>$null
$isInstalled = $installedVersions | Select-String -Pattern ([regex]::Escape($requestedVersion)) -Quiet
if (-not $isInstalled) {
Write-Host "nvm: Node $requestedVersion not installed. Installing..." -ForegroundColor Yellow
& nvm.exe install $requestedVersion
}
& nvm.exe use $requestedVersion
} else {
& nvm.exe @args
}
}nvm use(no args) → reads.nvmrc, installs if needed, switches.nvm use 22,nvm install,nvm list, etc. → passed straight through tonvm.exeas normal.- No prompt hook, no running on every command.
The key trick is calling
nvm.exeexplicitly inside the function to avoid infinite recursion — since the function itself is namednvm.