主题
环境变量
配置文件
创建 powershell 配置文件
bash
# Powershell 5 -> %userprofile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# Powershell 6+ -> %userprofile%\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
if (-not (Test-Path $profile)) { New-Item $profile -Force }
配置文件路径
- PowerShell 5:
%userprofile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
- PowerShell 6+:
%userprofile%\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
查看当前配置文件路径:
bash
$profile
打开配置文件
bash
Invoke-Item $profile
重新加载配置文件
bash
. $profile
查看环境变量
查看所有变量
powershell
Get-ChildItem Env:
查看特定变量
powershell
$env:VARIABLE_NAME
设置环境变量
临时设置(当前会话有效)
powershell
$env:VARIABLE_NAME = "value"
永久设置(对所有会话有效)
- 用户级别:powershell
[System.Environment]::SetEnvironmentVariable("VARIABLE_NAME", "value", "User")
- 系统级别:powershell
[System.Environment]::SetEnvironmentVariable("VARIABLE_NAME", "value", "Machine")
删除环境变量
临时删除
powershell
Remove-Item Env:VARIABLE_NAME
永久删除
- 用户级别:powershell
[System.Environment]::SetEnvironmentVariable("VARIABLE_NAME", $null, "User")
- 系统级别:powershell
[System.Environment]::SetEnvironmentVariable("VARIABLE_NAME", $null, "Machine")
修改 $PATH
临时添加
powershell
$env:Path += ";C:\new\path"
永久添加
- 用户级别:powershell
$currentPath = [System.Environment]::GetEnvironmentVariable("Path", "User") [System.Environment]::SetEnvironmentVariable("Path", "$currentPath;C:\new\path", "User")
- 系统级别:powershell
$currentPath = [System.Environment]::GetEnvironmentVariable("Path", "Machine") [System.Environment]::SetEnvironmentVariable("Path", "$currentPath;C:\new\path", "Machine")
常用环境变量
变量名 | 描述 |
---|---|
$env:USERNAME | 当前用户名 |
$env:USERPROFILE | 用户主目录 |
$env:PATH | 可执行文件搜索路径 |
$env:TEMP | 临时文件夹路径 |
$env:COMPUTERNAME | 计算机名 |
环境变量与脚本
在脚本中设置
powershell
$env:MY_VAR = "Hello"
在脚本中使用
powershell
Write-Output $env:MY_VAR
环境变量与 sudo
(PowerShell 无 sudo
)
PowerShell 没有 sudo
,但可以使用 Start-Process
以管理员身份运行命令:
powershell
Start-Process powershell -Verb RunAs -ArgumentList "-Command `"$env:MY_VAR`""
注意事项
- 变量名不区分大小写。
- 修改系统级别变量需要管理员权限。
配置代理
bash
$env:HTTP_PROXY = "http://127.0.0.1:10808"
$env:HTTPS_PROXY = "http://127.0.0.1:10808"