Setting Windows PowerShell environment variables

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

    My suggestion is this one:

    I have tested this to add C:\oracle\x64\bin to environment variable Path permanently and this works fine.

    $ENV:PATH
    

    The first way is simply to do:

    $ENV:PATH=”$ENV:PATH;c:\path\to\folder”
    

    But this change isn’t permanent. $env:path will default back to what it was before as soon as you close your PowerShell terminal and reopen it again. That’s because you have applied the change at the session level and not at the source level (which is the registry level). To view the global value of $env:path, do:

    Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment’ -Name PATH
    

    Or more specifically:

    (Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment’ -Name PATH).path
    

    Now to change this, first we capture the original path that needs to be modified:

    $oldpath = (Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment’ -Name PATH).path
    

    Now we define what the new path should look like. In this case we are appending a new folder:

    $newpath = “$oldpath;c:\path\to\folder”
    

    Note: Be sure that the $newpath looks how you want it to look. If not, then you could damage your OS.

    Now apply the new value:

    Set-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment’ -Name PATH -Value $newPath
    

    Now do one final check that it looks like how you expect it to:

    (Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment’ -Name PATH).Path
    

    You can now restart your PowerShell terminal (or even reboot the machine) and see that it doesn’t rollback to its old value again.

    Note the ordering of the paths may change so that it’s in alphabetical order, so make sure you check the whole line. To make it easier, you can split the output into rows by using the semi-colon as a delimiter:

    ($env:path).split(“;”)
    
    0 讨论(0)
  • 2020-11-22 11:27

    If, some time during a PowerShell session, you need to append to the PATH environment variable temporarily, you can do it this way:

    $env:Path += ";C:\Program Files\GnuWin32\bin"
    
    0 讨论(0)
  • 2020-11-22 11:27

    Only the answers that push the value into the registry affect a permanent change (so the majority of answers on this thread, including the accepted answer, do not permanently affect the Path).

    The following function works for both Path / PSModulePath and for User / System types. It will also add the new path to the current session by default.

    function AddTo-Path {
        param ( 
            [string]$PathToAdd,
            [Parameter(Mandatory=$true)][ValidateSet('System','User')][string]$UserType,
            [Parameter(Mandatory=$true)][ValidateSet('Path','PSModulePath')][string]$PathType
        )
    
        # AddTo-Path "C:\XXX" "PSModulePath" 'System' 
        if ($UserType -eq "System" ) { $RegPropertyLocation = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment' }
        if ($UserType -eq "User"   ) { $RegPropertyLocation = 'HKCU:\Environment' } # also note: Registry::HKEY_LOCAL_MACHINE\ format
        $PathOld = (Get-ItemProperty -Path $RegPropertyLocation -Name $PathType).$PathType
        "`n$UserType $PathType Before:`n$PathOld`n"
        $PathArray = $PathOld -Split ";" -replace "\\+$", ""
        if ($PathArray -notcontains $PathToAdd) {
            "$UserType $PathType Now:"   # ; sleep -Milliseconds 100   # Might need pause to prevent text being after Path output(!)
            $PathNew = "$PathOld;$PathToAdd"
            Set-ItemProperty -Path $RegPropertyLocation -Name $PathType -Value $PathNew
            Get-ItemProperty -Path $RegPropertyLocation -Name $PathType | select -ExpandProperty $PathType
            if ($PathType -eq "Path") { $env:Path += ";$PathToAdd" }                  # Add to Path also for this current session
            if ($PathType -eq "PSModulePath") { $env:PSModulePath += ";$PathToAdd" }  # Add to PSModulePath also for this current session
            "`n$PathToAdd has been added to the $UserType $PathType"
        }
        else {
            "'$PathToAdd' is already in the $UserType $PathType. Nothing to do."
        }
    }
    
    # Add "C:\XXX" to User Path (but only if not already present)
    AddTo-Path "C:\XXX" "User" "Path"
    
    # Just show the current status by putting an empty path
    AddTo-Path "" "User" "Path"
    
    0 讨论(0)
  • 2020-11-22 11:28

    You can also modify user/system environment variables permanently (i.e. will be persistent across shell restarts) with the following:

    Modify a system environment variable

    [Environment]::SetEnvironmentVariable
         ("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
    

    Modify a user environment variable

    [Environment]::SetEnvironmentVariable
         ("INCLUDE", $env:INCLUDE, [System.EnvironmentVariableTarget]::User)
    

    Usage from comments - add to the system environment variable

    [Environment]::SetEnvironmentVariable(
        "Path",
        [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine) + ";C:\bin",
        [EnvironmentVariableTarget]::Machine)
    

    String based solution is also possible if you don't want to write types

    [Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\bin", "Machine")
    
    0 讨论(0)
  • 2020-11-22 11:29

    This sets the path for the current session and prompts the user to add it permanently:

    function Set-Path {
        param([string]$x)
        $Env:Path+= ";" +  $x
        Write-Output $Env:Path
        $write = Read-Host 'Set PATH permanently ? (yes|no)'
        if ($write -eq "yes")
        {
            [Environment]::SetEnvironmentVariable("Path",$env:Path, [System.EnvironmentVariableTarget]::User)
            Write-Output 'PATH updated'
        }
    }
    

    You can add this function to your default profile, (Microsoft.PowerShell_profile.ps1), usually located at %USERPROFILE%\Documents\WindowsPowerShell.

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

    Changing the actual environment variables can be done by using the env: namespace / drive information. For example, this code will update the path environment variable:

    $env:Path = "SomeRandomPath";             (replaces existing path) 
    $env:Path += ";SomeRandomPath"            (appends to existing path)
    

    There are ways to make environment settings permanent, but if you are only using them from PowerShell, it's probably a lot better to use your profile to initiate the settings. On startup, PowerShell will run any .ps1 files it finds in the WindowsPowerShell directory under My Documents folder. Typically you have a profile.ps1 file already there. The path on my computer is

    C:\Users\JaredPar\Documents\WindowsPowerShell\profile.ps1
    
    0 讨论(0)
提交回复
热议问题