最近重装系统了,又需要重新配置开发环境涉及到很多环境变量的设置,所以写了个批处理脚本一键设置环境变量。使用时要注意bat文件的编码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
chcp 65001
@echo off
if exist "%SystemRoot%\SysWOW64" path %path%;%windir%\SysNative;%SystemRoot%\SysWOW64;%~dp0
bcdedit >nul
if '%errorlevel%' NEQ '0' (goto UACPrompt) else (goto UACAdmin)
:UACPrompt
%1 start "" mshta vbscript:createobject("shell.application").shellexecute("""%~0""","::",,"runas",1)(window.close)&exit
exit /B
:UACAdmin
cd /d "%~dp0"
@echo 当前运行路径是:%CD%
@echo 已获取管理员权限
set temp_ps_file="%temp%\temp.ps1"
@echo "" > "%temp_ps_file%"
for /f "delims=:" %%i in ('findstr /n "^:powerScript$" "%~f0"') do (
    more +%%i "%~f0" >> "%temp_ps_file%"
)

powershell -ExecutionPolicy RemoteSigned -file "%temp_ps_file%"
@echo 操作完成
pause
exit

:powerScript

function AppendPathEnv {
    param($Value)
    $PathStr = (New-Object -ComObject WScript.Shell).RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path")
    if ($PathStr.EndsWith(';')) {
        $PathStr = $PathStr.Remove($PathStr.LastIndexOf(';'))
    }
    $PathStr = "$PathStr;$Value"
    [environment]::SetEnvironmentvariable("Path", "$PathStr", "Machine")
}

function SetEnv {
    param($Key, $Value)
    [environment]::SetEnvironmentvariable("$Key", "$Value", "Machine")
}

SetEnv -Key  "CARGO_HOME" -Value "S:\Dev\rust\cargo"
SetEnv -Key  "RUSTUP_HOME" -Value "S:\Dev\rust\rustup"
SetEnv -Key  "MAVEN_HOME" -Value "D:\Dev\apache-maven-3.5.0"
SetEnv -Key  "JAVA_HOME" -Value "C:\Program Files\Java\jdk1.8.0_301"

$appendPath = "";
$appendPath = $appendPath + ";S:\Dev\mingw64\bin"
$appendPath = $appendPath + ";%CARGO_HOME%\bin"
$appendPath = $appendPath + ";%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin"
$appendPath = $appendPath + ";%MAVEN_HOME%\bin"

AppendPathEnv -Value $appendPath