Windows环境变量一键导出/导入工具(PowerShell版)
简介
提供两个PowerShell脚本,可快速导出和导入Windows环境变量,方便系统迁移、备份和恢复。
快速使用
PS D:\DownLoad> Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
PS D:\DownLoad> .\Simple-Export-Env.ps1
Creating formatted export file...
Export completed successfully!
Total variables exported: 0
PATH entries found: 32
Files created:
1. C:\EnvVars_20260205_232045.txt (raw output)
2. C:\EnvVars_Export.txt (formatted output)
Press any key to continue...
PS D:\DownLoad>
PS D:\DownLoad>
PS D:\DownLoad> .\QuickImportEnv.ps1
=== Environment Variables Import Tool ===
File: C:\EnvironmentVariables.txt
File size: 64 bytes
Created: 02/05/2026 23:20:45
WARNING: This will import environment variables to your user profile.
Do you want to continue? (Y/N): y
Importing environment variables...
鉁?AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
=== Import Summary ===
Successfully imported: 1 variables
Skipped system variables: 0
Errors: 0
=== Important Notes ===
1. User environment variables are saved to registry
2. They will be available in NEW command windows
3. To use them in current window, you need to refresh
Refresh environment in current PowerShell window? (Y/N):
Done. Press any key to exit...
PS D:\DownLoad>完整工具包
增强版导出脚本(包含系统/用户变量)
Simple-Export-Env.ps1
powershell
# Quick Environment Variables Import Script
# Safe version with error handling
# Check if file path is provided
if ($args.Count -gt 0) {
$ImportFile = $args[0]
} else {
$ImportFile = "C:\EnvironmentVariables.txt"
}
# Display header
Write-Host "=== Environment Variables Import Tool ===" -ForegroundColor Cyan
Write-Host "File: $ImportFile" -ForegroundColor White
Write-Host ""
# Check if file exists
if (-not (Test-Path $ImportFile)) {
Write-Host "ERROR: File not found!" -ForegroundColor Red
Write-Host "Looking for: $ImportFile" -ForegroundColor Yellow
Write-Host ""
Write-Host "Please make sure:"
Write-Host "1. The file exists in the specified location" -ForegroundColor White
Write-Host "2. You have provided the correct path" -ForegroundColor White
Write-Host ""
Write-Host "Usage examples:" -ForegroundColor Green
Write-Host " .\QuickImportEnv.ps1" -ForegroundColor Cyan
Write-Host " .\QuickImportEnv.ps1 C:\MyVars.txt" -ForegroundColor Cyan
Write-Host ""
pause
exit 1
}
# Show file info
$fileInfo = Get-Item $ImportFile
Write-Host "File size: $($fileInfo.Length) bytes" -ForegroundColor Gray
Write-Host "Created: $($fileInfo.CreationTime)" -ForegroundColor Gray
Write-Host ""
# Ask for confirmation
Write-Host "WARNING: This will import environment variables to your user profile." -ForegroundColor Yellow
Write-Host "Do you want to continue? (Y/N): " -ForegroundColor Yellow -NoNewline
$confirm = Read-Host
if ($confirm -notmatch "^[Yy]$") {
Write-Host "Import cancelled." -ForegroundColor Gray
exit 0
}
# Import variables
Write-Host ""
Write-Host "Importing environment variables..." -ForegroundColor Cyan
$importCount = 0
$skipCount = 0
$errorCount = 0
# Read file line by line
$lines = Get-Content $ImportFile
foreach ($line in $lines) {
$line = $line.Trim()
# Skip empty lines and comments
if ([string]::IsNullOrEmpty($line)) {
continue
}
if ($line.StartsWith("#") -or $line.StartsWith("//") -or $line.StartsWith("--")) {
continue
}
# Skip section headers
if ($line.Contains("===") -or $line.Contains("---") -or
$line.Contains("[") -or $line.ToUpper().Contains("ENVIRONMENT")) {
continue
}
# Check if it's a variable assignment
if ($line.Contains("=")) {
# Split into name and value
$parts = $line.Split("=", 2)
if ($parts.Count -eq 2) {
$varName = $parts[0].Trim()
$varValue = $parts[1].Trim()
# Skip certain system variables
$skipNames = @("Path", "PATH", "PATHEXT", "OS", "COMPUTERNAME",
"USERNAME", "USERPROFILE", "SYSTEMROOT", "WINDIR",
"PROCESSOR_ARCHITECTURE", "PROGRAMFILES")
if ($skipNames -contains $varName) {
$skipCount++
continue
}
# Try to import the variable
try {
# Set as user environment variable
[Environment]::SetEnvironmentVariable($varName, $varValue, "User")
Write-Host " ✓ $varName" -ForegroundColor Green
$importCount++
} catch {
Write-Host " ✗ $varName (Error)" -ForegroundColor Red
$errorCount++
}
}
}
}
# Summary
Write-Host ""
Write-Host "=== Import Summary ===" -ForegroundColor Cyan
Write-Host "Successfully imported: $importCount variables" -ForegroundColor Green
Write-Host "Skipped system variables: $skipCount" -ForegroundColor Yellow
Write-Host "Errors: $errorCount" -ForegroundColor Red
# Post-import instructions
Write-Host ""
Write-Host "=== Important Notes ===" -ForegroundColor Yellow
Write-Host "1. User environment variables are saved to registry" -ForegroundColor White
Write-Host "2. They will be available in NEW command windows" -ForegroundColor White
Write-Host "3. To use them in current window, you need to refresh" -ForegroundColor White
Write-Host ""
# Ask to refresh
Write-Host "Refresh environment in current PowerShell window? (Y/N): " -ForegroundColor Cyan -NoNewline
$refresh = Read-Host
if ($refresh -match "^[Yy]$") {
Write-Host "Refreshing environment variables..." -ForegroundColor Yellow
# Refresh PATH variable
$newPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ($newPath) {
$currentPath = $env:Path
$env:Path = $newPath + ";" + $currentPath
Write-Host "PATH variable refreshed" -ForegroundColor Green
}
# Reload other variables from user profile
Get-ChildItem Env: | Where-Object {
$_.Name -notin @("Path", "PSModulePath", "USERNAME", "COMPUTERNAME")
} | ForEach-Object {
$userValue = [Environment]::GetEnvironmentVariable($_.Name, "User")
if ($userValue) {
Set-Item -Path "Env:\$($_.Name)" -Value $userValue -Force
}
}
Write-Host "Environment refreshed!" -ForegroundColor Green
}
Write-Host ""
Write-Host "Done. Press any key to exit..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")批量导入脚本
QuickImportEnv.ps1
powershell
# 简化版环境变量导出脚本
# 避免编码问题
# 设置输出文件
$outputFile = "C:\EnvVars_Export.txt"
# 获取当前日期时间
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
# 方法1:使用set命令导出(最兼容)
Write-Host "Exporting environment variables..." -ForegroundColor Yellow
cmd /c "set > C:\EnvVars_$timestamp.txt"
# 方法2:使用PowerShell获取并格式化
Write-Host "`nCreating formatted export file..." -ForegroundColor Yellow
# 创建标题
"=========================================" | Out-File $outputFile
"ENVIRONMENT VARIABLES EXPORT" | Out-File $outputFile -Append
"Exported: $(Get-Date)" | Out-File $outputFile -Append
"=========================================" | Out-File $outputFile -Append
"" | Out-File $outputFile -Append
# 导出所有环境变量
$envVars = Get-ChildItem Env: | Sort-Object Name
$count = 0
foreach ($item in $envVars) {
"$($item.Name)=$($item.Value)" | Out-File $outputFile -Append -Encoding ASCII
$count++
}
# 导出PATH详细信息
"`n" | Out-File $outputFile -Append
"=== PATH VARIABLE DETAILS ===" | Out-File $outputFile -Append
"`nPATH entries (split by ';'):" | Out-File $outputFile -Append
$pathEntries = $env:Path -split ';' | Where-Object { $_ -ne '' }
$pathCount = 0
foreach ($entry in $pathEntries) {
"[$pathCount] $entry" | Out-File $outputFile -Append -Encoding ASCII
$pathCount++
}
Write-Host "`nExport completed successfully!" -ForegroundColor Green
Write-Host "Total variables exported: $count" -ForegroundColor Green
Write-Host "PATH entries found: $pathCount" -ForegroundColor Green
Write-Host "`nFiles created:" -ForegroundColor Cyan
Write-Host "1. C:\EnvVars_$timestamp.txt (raw output)" -ForegroundColor White
Write-Host "2. $outputFile (formatted output)" -ForegroundColor White
# 显示文件位置
Write-Host "`nPress any key to continue..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")使用场景
1. 系统迁移
powershell
# 旧电脑:导出
.\Export-EnvVars.ps1
# 新电脑:导入
.\Import-EnvVars.ps12. 环境备份
powershell
# 定期备份
$backupDir = "C:\EnvBackups"
New-Item -ItemType Directory -Force -Path $backupDir
$backupFile = "$backupDir\EnvBackup_$(Get-Date -Format 'yyyyMMdd').txt"
Get-ChildItem Env: | ForEach-Object { "$($_.Name)=$($_.Value)" } | Out-File $backupFile3. 批量设置开发环境
powershell
# 创建开发环境配置文件
@"
JAVA_HOME=C:\Program Files\Java\jdk-17
MAVEN_HOME=C:\Program Files\Apache\Maven
NODE_PATH=C:\Program Files\nodejs
"@ | Out-File "C:\DevEnv.txt"
# 导入开发环境
Get-Content "C:\DevEnv.txt" | ForEach-Object {
if ($_ -match "(.+)=(.+)") {
[Environment]::SetEnvironmentVariable($matches[1], $matches[2], "User")
}
}