快轉到主要內容

透過 Powershell 設定 PATH 環境變數

· 0
目錄

通常來說,在 Windows 上要設定環境變數,都需要打開「系統」的「進階系統設定」,然後在「進階」分頁中的「環境變數」中設定。但是,如果要透過程式來設定環境變數,完成一定的自動化,可以透過 Powershell 來完成。

本篇文章將會介紹如何透過 Powershell 來設定環境變數。

透過 Powershell 設定環境變數 #

# 設定要加入環境變數中的路徑
$path_array = @(
    'C:\Program Files\Git\bin',
    '$HOME\AppData\Roaming\Python\Scripts'
)

for ($i = 0; $i -lt $path_array.Count; $i++) {
    $InstallFolder = $null
    $InstallFolder = $path_array[$i]

    # $env:Path, [Environment]::GetEnvironmentVariable('PATH'), and setx all expand
    # variables (e.g. %JAVA_HOME%) in the value. Writing the expanded paths back
    # into the environment would be destructive so instead, read the path directly
    # from the registry with the DoNotExpandEnvironmentNames option and write that
    # value back using the non-destructive [Environment]::SetEnvironmentVariable
    # which also broadcasts environment variable changes to Windows.
    try {
        $registryKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
        $originalPath = $registryKey.GetValue(`
            'PATH', `
            '', `
            [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames `
        )
        $pathParts = $originalPath -split ';'

        if (!($pathParts -contains $InstallFolder)) {
            Write-Host "Adding $InstallFolder to PATH"

            # SetEnvironmentVariable broadcasts the "Environment" change to
            # Windows and is NOT destructive (e.g. expanding variables)
            [Environment]::SetEnvironmentVariable(
                'PATH', `
                "$originalPath;$InstallFolder", `
                [EnvironmentVariableTarget]::User`
            )

            # Also add the path to the current session
            $env:PATH += ";$InstallFolder"
        } else {
            Write-Host "An entry for $InstallFolder is already in PATH"
        }
    } finally {
        if ($registryKey) {
            $registryKey.Close()
        }
    }
}

相關連結 #

如何透過 PowerShell 自動寫入執行檔路徑到 PATH 使用者環境變數 | The Will Will Web (miniasp.com)

Related

在 Windows 上透過 Chocolatey 使用命令列管理軟體
· 0
ImageMagick 常用指令
· 0
Sublime Text 3/4 常用設定與指令
· 0

boba-icon
請我喝珍奶!