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)

標籤 :

相關文章

如何調整 Linux 系統時區

如何調整 Linux 系統時區

最近透過 docker 編譯程式後,發現時間對不上,原來是時區沒有設定的問題。 本來想說時區設定應該滿容易的,沒想到因為 docker 設定時不會互動,所以用一般在 Ubuntu 上使

閱讀更多
使用 OpenSSH 替沒有固定 IP 的本地主機 (WSL2) 建立反向 TCP 遠端通道 (Ngrok 免費替代)

使用 OpenSSH 替沒有固定 IP 的本地主機 (WSL2) 建立反向 TCP 遠端通道 (Ngrok 免費替代)

若我們希望將本地主機的服務,例如 ssh 伺服器供外部連線,但我們又沒有固定 IP 時,我們可以使用 OpenSSH 建立反向 TCP 遠端通道,讓外部主機可以透過這個通道連線到

閱讀更多
使用 Visual Studio Code 跨平台 C/C++ 開發環境全攻略

使用 Visual Studio Code 跨平台 C/C++ 開發環境全攻略

幾年前曾經使用 Visual Studio Code 在 Windows 上開發 C/C++,曾寫了一篇文章 記錄過程,但是當時只有在 Windows 上開發,最近又有需求要撰寫一些 C/C++ 專案,並且這次會在 macOS 和 Linux 上

閱讀更多