目录

工欲善其事

实践出真知

活跃标签: linux java mysql 待分类 windows js win10 springboot pdf idea docker 电路 nginx esp32 macOS git vue Arduino maven ffmpeg

存档:

X

使用PowerShell配置环境变量

1. 临时设置环境变量 (仅当前会话有效)

powershell

# 设置临时环境变量
$env:MY_VARIABLE = "my_value"

# 查看环境变量
Write-Output $env:MY_VARIABLE

# 添加到PATH
$env:PATH += ";C:\my\custom\path"

2. 永久设置用户级环境变量

powershell

# 设置用户级环境变量
[System.Environment]::SetEnvironmentVariable("MY_VARIABLE", "my_value", "User")

# 添加用户级PATH
$oldPath = [System.Environment]::GetEnvironmentVariable("PATH", "User")
$newPath = $oldPath + ";C:\my\custom\path"
[System.Environment]::SetEnvironmentVariable("PATH", $newPath, "User")

# 立即生效 (需要重启进程)
$env:MY_VARIABLE = "my_value"
$env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "User") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "Machine")

3. 永久设置系统级环境变量 (需要管理员权限)

powershell

# 以管理员身份运行
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {  
    Start-Process powershell -Verb runAs -ArgumentList "-file", $MyInvocation.MyCommand.Path
    exit
}

# 设置系统级环境变量
[System.Environment]::SetEnvironmentVariable("MY_VARIABLE", "my_value", "Machine")

# 添加系统级PATH
$oldPath = [System.Environment]::GetEnvironmentVariable("PATH", "Machine")
$newPath = $oldPath + ";C:\my\custom\path"
[System.Environment]::SetEnvironmentVariable("PATH", $newPath, "Machine")

# 刷新环境变量 (对当前会话生效)
$env:MY_VARIABLE = "my_value"
$env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine")

4. 检查环境变量

powershell

# 查看所有环境变量
Get-ChildItem env:

# 查看特定环境变量
Write-Output $env:PATH

# 查看用户级环境变量
[System.Environment]::GetEnvironmentVariable("MY_VARIABLE", "User")

# 查看系统级环境变量
[System.Environment]::GetEnvironmentVariable("MY_VARIABLE", "Machine")

标题:使用PowerShell配置环境变量
作者:llilei
地址:http://solo.llilei.work/articles/2025/07/26/1753513198463.html