Powershell 環境變數設定:自動化您的 Windows 設定

Powershell 環境變數設定:自動化您的 Windows 設定

目錄

在 Windows 中,手動設定環境變數通常需要通過系統進階系統設定來進行,這個過程可能比較繁瑣。幸運的是,我們可以利用 Powershell 來實現自動化的環境變數設定。在本篇文章中,我將指導您如何使用 Powershell 來高效地設定和管理 Windows 的環境變數,從而簡化整個過程。這不僅節省時間,而且也提高了配置工作的效率。

透過 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)

標籤 :
分享 :