Setting Windows PowerShell environment variables

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

    As Jonathan Leaders mentioned here, it is important to run the command/script elevated to be able to change environment variables for 'machine', but running some commands elevated doesn't have to be done with the Community Extensions, so I'd like to modify and extend JeanT's answer in a way, that changing machine variables also can be performed even if the script itself isn't run elevated:

    function Set-Path ([string]$newPath, [bool]$permanent=$false, [bool]$forMachine=$false )
    {
        $Env:Path += ";$newPath"
    
        $scope = if ($forMachine) { 'Machine' } else { 'User' }
    
        if ($permanent)
        {
            $command = "[Environment]::SetEnvironmentVariable('PATH', $env:Path, $scope)"
            Start-Process -FilePath powershell.exe -ArgumentList "-noprofile -command $Command" -Verb runas
        }
    
    }
    

提交回复
热议问题