Setting Windows PowerShell environment variables

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

    To be clear, the 1990's Windows way of click on Start, right click on This PC, and choose Properties, and then select Advanced system settings, and then in the dialog box that pops up, select Environment Variables, and in the list double clicking on PATH and then using the New, Edit, Move Up and Move Down all still work for changing the PATH. Power shell, and the rest of Windows get whatever you set here.

    Yes you can use these new methods, but the old one still works. And at the base level all of the permanent change methods are controlled ways of editing your registry files.

    0 讨论(0)
  • 2020-11-22 11:35

    Although the current accepted answer works in the sense that the path variable gets permanently updated from the context of PowerShell, it doesn't actually update the environment variable stored in the Windows registry.

    To achieve that, you can obviously use PowerShell as well:

    $oldPath=(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path
    
    $newPath=$oldPath+’;C:\NewFolderToAddToTheList\’
    
    Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH –Value $newPath
    

    More information is in blog post Use PowerShell to Modify Your Environmental Path

    If you use PowerShell community extensions, the proper command to add a path to the environment variable path is:

    Add-PathVariable "C:\NewFolderToAddToTheList" -Target Machine
    
    0 讨论(0)
  • 2020-11-22 11:36

    Within PowerShell, one can navigate to the environment variable directory by typing:

    Set-Location Env:
    

    This will bring you to the Env:> directory. From within this directory:

    To see all environment variables, type:

    Env:\> Get-ChildItem
    

    To see a specific environment variable, type:

    Env:\> $Env:<variable name>, e.g. $Env:Path
    

    To set an environment variable, type:

    Env:\> $Env:<variable name> = "<new-value>", e.g. $Env:Path="C:\Users\"
    

    To remove an environment variable, type:

    Env:\> remove-item Env:<variable name>, e.g. remove-item Env:SECRET_KEY
    

    More information is in About Environment Variables.

    0 讨论(0)
  • 2020-11-22 11:43

    Most answers aren't addressing UAC. This covers UAC issues.

    First install PowerShell Community Extensions: choco install pscx via http://chocolatey.org/ (you may have to restart your shell environment).

    Then enable pscx

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx
    

    Then use Invoke-Elevated

    Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR
    
    0 讨论(0)
  • 2020-11-22 11:44

    I tried to optimise SBF's and Michael's code a bit to make it more compact.

    I am relying on PowerShell's type coercion where it automatically converts strings to enum values, so I didn't define the lookup dictionary.

    I also pulled out the block that adds the new path to the list based on a condition, so that work is done once and stored in a variable for re-use.

    It is then applied permanently or just to the Session depending on the $PathContainer parameter.

    We can put the block of code in a function or a ps1 file that we call directly from the command prompt. I went with DevEnvAddPath.ps1.

    param(
        [Parameter(Position=0,Mandatory=$true)][String]$PathChange,
    
        [ValidateSet('Machine', 'User', 'Session')]
        [Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session',
        [Parameter(Position=2,Mandatory=$false)][Boolean]$PathPrepend=$false
    )
    
    [String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
    $PathPersisted = $ConstructedEnvPath -split ';';
    
    if ($PathPersisted -notcontains $PathChange) {
        $PathPersisted = $(switch ($PathPrepend) { $true{,$PathChange + $PathPersisted;} default{$PathPersisted + $PathChange;} }) | Where-Object { $_ };
    
        $ConstructedEnvPath = $PathPersisted -join ";";
    }
    
    if ($PathContainer -ne 'Session') 
    {
        # Save permanently to Machine, User
        [Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
    }
    
    # Update the current session
    ${env:Path} = $ConstructedEnvPath;
    

    I do something similar for a DevEnvRemovePath.ps1.

    param(
        [Parameter(Position=0,Mandatory=$true)][String]$PathChange,
    
        [ValidateSet('Machine', 'User', 'Session')]
        [Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session'
    )
    
    [String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
    $PathPersisted = $ConstructedEnvPath -split ';';
    
    if ($PathPersisted -contains $PathChange) {
        $PathPersisted = $PathPersisted | Where-Object { $_ -ne $PathChange };
    
        $ConstructedEnvPath = $PathPersisted -join ";";
    }
    
    if ($PathContainer -ne 'Session') 
    {
        # Save permanently to Machine, User
        [Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
    }
    
    # Update the current session
    ${env:Path} = $ConstructedEnvPath;
    

    So far, they seem to work.

    0 讨论(0)
  • 2020-11-22 11:44

    do not make headaches for yourself, want a simple, one line solution to add a permanent environment variable (open powershell in elevated mode):

    [Environment]::SetEnvironmentVariable("NewEnvVar", "NewEnvValue", "Machine")
    

    close the session and open it again to make things done


    in case that u want to modify/change that:

    [Environment]::SetEnvironmentVariable("oldEnvVar", "NewEnvValue", "Machine")
    


    in case that u want to delete/remove that:

    [Environment]::SetEnvironmentVariable("oldEnvVar", "", "Machine")
    
    0 讨论(0)
提交回复
热议问题