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)

標籤 :
comments powered by Disqus

相關文章

如何調整 Linux 系統時區

如何調整 Linux 系統時區

在 Debian/Ubuntu 上調整時區 檢查目前的時區設定 timedatectl 列出所有可用的時區 timedatectl list-timezones 設定時區 sudo timedatectl set-timezone Asia/Taipei sudo dpkg-reconfigure --frontend noninteractive tzdata 在 Docker 容器中調整時區 export TZ=Asia/Taipei ln -snf /usr/share/zoneinfo/$TZ /etc/localtime echo $TZ > /etc/timezone DEBIAN_FRONTEND="noninteractive" apt-get install -y tzdata

閱讀更多
羅技 MX 滑鼠系列大比拚:優缺點全解析

羅技 MX 滑鼠系列大比拚:優缺點全解析

今天我要帶大家深入探索 羅技的 MX 滑鼠系列 。羅技的 MX 滑鼠一直以來都是市場上的熱門選擇,不僅因為其出色的性能,還有其獨特的設計。但是,每一款 MX 滑鼠

閱讀更多
如何在 Hugo 網站中加入 LikeCoin 讚賞鍵提升創作收入

如何在 Hugo 網站中加入 LikeCoin 讚賞鍵提升創作收入

因為我本身是 LikeCoin 支持者,也是推崇文章開源但內容有價的創作者。 因此希望即便從 WordPress 轉移至 Hugo ,依然能夠使用 LikeCoin 作為連結我與讀者間的橋梁。 本文以 hugo v0.114.1 搭配 LoveIt

閱讀更多