Setting Windows PowerShell environment variables

前端 未结 18 1770
日久生厌
日久生厌 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:22

    Building on @Michael Kropat's answer I added a parameter to prepend the new path to the existing PATHvariable and a check to avoid the addition of a non-existing path:

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

提交回复
热议问题