Setting Windows PowerShell environment variables

前端 未结 18 1913
日久生厌
日久生厌 2020-11-22 11:03

I have found out that setting the PATH environment variable affects only the old command prompt. PowerShell seems to have different environment settings. How do I change the

18条回答
  •  迷失自我
    2020-11-22 11:21

    Like JeanT's answer, I wanted an abstraction around adding to the path. Unlike JeanT's answer I needed it to run without user interaction. Other behavior I was looking for:

    • Updates $env:Path so the change takes effect in the current session
    • Persists the environment variable change for future sessions
    • Doesn't add a duplicate path when the same path already exists

    In case it's useful, here it is:

    function Add-EnvPath {
        param(
            [Parameter(Mandatory=$true)]
            [string] $Path,
    
            [ValidateSet('Machine', 'User', 'Session')]
            [string] $Container = 'Session'
        )
    
        if ($Container -ne 'Session') {
            $containerMapping = @{
                Machine = [EnvironmentVariableTarget]::Machine
                User = [EnvironmentVariableTarget]::User
            }
            $containerType = $containerMapping[$Container]
    
            $persistedPaths = [Environment]::GetEnvironmentVariable('Path', $containerType) -split ';'
            if ($persistedPaths -notcontains $Path) {
                $persistedPaths = $persistedPaths + $Path | where { $_ }
                [Environment]::SetEnvironmentVariable('Path', $persistedPaths -join ';', $containerType)
            }
        }
    
        $envPaths = $env:Path -split ';'
        if ($envPaths -notcontains $Path) {
            $envPaths = $envPaths + $Path | where { $_ }
            $env:Path = $envPaths -join ';'
        }
    }
    

    Check out my gist for the corresponding Remove-EnvPath function.

提交回复
热议问题