# 定义环境变量的作用域: "User" (用户级) 或 "Machine" (系统级).
# 设置为 "Machine" 需要以管理员身份运行 PowerShell.
$scope = "User" 

Write-Host "Setting permanent environment variables for scope: $scope"
Write-Host "IMPORTANT: These variables will be available in NEW PowerShell or CMD windows." -ForegroundColor Yellow
Write-Host ""

# 这是一个辅助函数,用于设置永久变量并打印状态
function Set-PermanentEnvVar {
    param (
        [string]$Name,
        [string]$Value,
        [string]$TargetScope
    )
    try {
        # 1. 永久设置环境变量
        [System.Environment]::SetEnvironmentVariable($Name, $Value, $TargetScope)
        
        # 2. 【已修正】为当前会话也设置该变量,以便立即生效
        Set-Item -Path "env:$Name" -Value $Value
        
        Write-Host "[SUCCESS] Set '$Name'" -ForegroundColor Green
    }
    catch {
        Write-Host "[FAILED]  Could not set '$Name'. Run as Administrator if scope is 'Machine'." -ForegroundColor Red
    }
}

# --- 需要设置的变量列表 ---

Set-PermanentEnvVar "POSTGRES_HOST" "localhost" $scope
Set-PermanentEnvVar "POSTGRES_PORT" "35432" $scope
Set-PermanentEnvVar "POSTGRES_USERNAME" "admin" $scope
Set-PermanentEnvVar "POSTGRES_PASSWORD" "123qwe." $scope

Write-Host ""
Write-Host "All variables have been set. They are also available in this current session." -ForegroundColor Cyan

标签: windows, shell

添加新评论