Naposledy aktivní 1 month ago

把 Linux 风格的 .myenv 文件(每行 export VAR=value)直接导入到 当前用户的 Windows 永久环境变量 中

Revize d6620a185214880d50b95645897f605a40460665

import-env.ps1 Raw
1<#
2.SYNOPSIS
3 将 Linux 风格的 .env / .myenv 文件导入到 Windows 当前用户(或系统)环境变量
4.USAGE
5 .\Import-LinuxEnv.ps1 -FilePath "C:\myconfig\.myenv"
6 .\Import-LinuxEnv.ps1 .\.myenv # 自动识别当前目录文件
7 .\Import-LinuxEnv.ps1 .\.myenv -System # 写入系统变量(需要管理员)
8#>
9
10param(
11 [Parameter(Mandatory=$true, Position=0)][string]$FilePath,
12 [switch]$System # 加这个参数就写入系统环境变量(需要管理员权限)
13)
14
15$ErrorActionPreference = "Stop"
16
17# 解决相对路径
18$FilePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($FilePath)
19
20if (-not (Test-Path $FilePath)) {
21 Write-Error "文件不存在:$FilePath"
22 exit 1
23}
24
25$target = if ($System) { "Machine" } else { "User" }
26$needAdmin = $System -and -not ([Security.Principal.WindowsPrincipal] `
27 [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
28 [Security.Principal.WindowsBuiltInRole]::Administrator)
29
30if ($needAdmin) {
31 Write-Error "写入系统环境变量需要管理员权限,请右键 → 以管理员身份运行 PowerShell"
32 exit 1
33}
34
35$successCount = 0
36Get-Content $FilePath | ForEach-Object {
37 $line = $_.Trim()
38 if ($line -eq "" -or $line.StartsWith("#")) { return }
39
40 if ($line -match '^\s*export\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+?)\s*$' -or
41 $line -match '^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.+?)\s*$') {
42
43 $name = $matches[1]
44 $value = $matches[2]
45
46 # 去掉最外层成对的单/双引号
47 $value = $value -replace '^"(.*)"$' , '$1'
48 $value = $value -replace "^'(.*)'$", '$1'
49
50 [Environment]::SetEnvironmentVariable($name, $value, $target)
51 Write-Host "已设置 $name = $value" -ForegroundColor Green
52 $successCount++
53 }
54}
55
56Write-Host "`n成功导入 $successCount 个环境变量到 $target 环境" -ForegroundColor Cyan
57Write-Host "请关闭当前终端后重新打开(或重启电脑)使变量生效" -ForegroundColor Yellow