<# .SYNOPSIS 将 Linux 风格的 .env / .myenv 文件导入到 Windows 当前用户(或系统)环境变量 .USAGE .\Import-LinuxEnv.ps1 -FilePath "C:\myconfig\.myenv" .\Import-LinuxEnv.ps1 .\.myenv # 自动识别当前目录文件 .\Import-LinuxEnv.ps1 .\.myenv -System # 写入系统变量(需要管理员) #> param( [Parameter(Mandatory=$true, Position=0)][string]$FilePath, [switch]$System # 加这个参数就写入系统环境变量(需要管理员权限) ) $ErrorActionPreference = "Stop" # 解决相对路径 $FilePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($FilePath) if (-not (Test-Path $FilePath)) { Write-Error "文件不存在:$FilePath" exit 1 } $target = if ($System) { "Machine" } else { "User" } $needAdmin = $System -and -not ([Security.Principal.WindowsPrincipal] ` [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(` [Security.Principal.WindowsBuiltInRole]::Administrator) if ($needAdmin) { Write-Error "写入系统环境变量需要管理员权限,请右键 → 以管理员身份运行 PowerShell" exit 1 } $successCount = 0 Get-Content $FilePath | ForEach-Object { $line = $_.Trim() if ($line -eq "" -or $line.StartsWith("#")) { return } if ($line -match '^\s*export\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+?)\s*$' -or $line -match '^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+?)\s*$') { $name = $matches[1] $value = $matches[2] # 去掉最外层成对的单/双引号 $value = $value -replace '^"(.*)"$' , '$1' $value = $value -replace "^'(.*)'$", '$1' [Environment]::SetEnvironmentVariable($name, $value, $target) Write-Host "已设置 $name = $value" -ForegroundColor Green $successCount++ } } Write-Host "`n成功导入 $successCount 个环境变量到 $target 环境" -ForegroundColor Cyan Write-Host "请关闭当前终端后重新打开(或重启电脑)使变量生效" -ForegroundColor Yellow