我发现设置PATH环境变量只影响旧的命令提示符。PowerShell似乎有不同的环境设置。如何更改PowerShell (v1)的环境变量?

注意:

我希望我的更改是永久性的,这样我就不必每次运行PowerShell时都设置它。PowerShell有配置文件吗?比如Unix上的Bash配置文件?


当前回答

所有建议永久更改的答案都有相同的问题:它们破坏了路径注册表值。

SetEnvironmentVariable将REG_EXPAND_SZ值%SystemRoot%\system32转换为c:\ windows \system32的REG_SZ值。

路径中的任何其他变量也会丢失。使用%myNewPath%添加新的将不再工作。

这里有一个脚本Set-PathVariable。我用来解决这个问题的ps1:

 [CmdletBinding(SupportsShouldProcess=$true)]
 param(
     [parameter(Mandatory=$true)]
     [string]$NewLocation)

 Begin
 {

 #requires –runasadministrator

     $regPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
     $hklm = [Microsoft.Win32.Registry]::LocalMachine

     Function GetOldPath()
     {
         $regKey = $hklm.OpenSubKey($regPath, $FALSE)
         $envpath = $regKey.GetValue("Path", "", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
         return $envPath
     }
 }

 Process
 {
     # Win32API error codes
     $ERROR_SUCCESS = 0
     $ERROR_DUP_NAME = 34
     $ERROR_INVALID_DATA = 13

     $NewLocation = $NewLocation.Trim();

     If ($NewLocation -eq "" -or $NewLocation -eq $null)
     {
         Exit $ERROR_INVALID_DATA
     }

     [string]$oldPath = GetOldPath
     Write-Verbose "Old Path: $oldPath"

     # Check whether the new location is already in the path
     $parts = $oldPath.split(";")
     If ($parts -contains $NewLocation)
     {
         Write-Warning "The new location is already in the path"
         Exit $ERROR_DUP_NAME
     }

     # Build the new path, make sure we don't have double semicolons
     $newPath = $oldPath + ";" + $NewLocation
     $newPath = $newPath -replace ";;",""

     if ($pscmdlet.ShouldProcess("%Path%", "Add $NewLocation")){

         # Add to the current session
         $env:path += ";$NewLocation"

         # Save into registry
         $regKey = $hklm.OpenSubKey($regPath, $True)
         $regKey.SetValue("Path", $newPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
         Write-Output "The operation completed successfully."
     }

     Exit $ERROR_SUCCESS
 }

我在一篇博文中更详细地解释了这个问题。

其他回答

大多数答案都没有涉及UAC。这涵盖了UAC问题。

首先通过http://chocolatey.org/安装PowerShell Community Extensions: choco install pscx(您可能需要重新启动shell环境)。

然后启用pscx

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

然后使用Invoke-Elevated

Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

就像JeanT的回答一样,我想要一个关于添加路径的抽象。与JeanT的回答不同,我需要它在没有用户交互的情况下运行。我寻找的其他行为:

更新$env:Path,使更改在当前会话中生效 为以后的会话持久化环境变量更改 当相同的路径已经存在时,不添加重复的路径

如果有用的话,这里是:

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 ';'
    }
}

检查我的要点对应的Remove-EnvPath函数。

只有将值推入注册表的答案才会影响永久更改(因此这个线程上的大多数答案,包括已接受的答案,不会永久影响Path)。

下面的函数适用于Path / PSModulePath和User / System类型。默认情况下,它还会将新路径添加到当前会话。

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"

在@ali Darabi的回答中编辑注册表键对我来说是最好的,但是 当我没有Powershell的权限时。所以我直接在regedit里编辑。

我想在这个回答中进一步展开这个主题。

重新启动Powershell也不足以传播更改。我必须打开任务管理器并重新启动explorer.exe以触发注册表的重新加载。

导航注册表可能相当乏味,所以为了保持用户友好的体验,你可以从Powershell执行这个:

REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit" /v "LastKey" /d "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" /f; regedit

它将最后打开的窗口设置为某个注册表路径,这样当您下次打开regedit时,它将以适当的键打开。

无痛苦的、一行的示例解决方案

尝试这三个命令来练习在PowerShell中设置和删除环境变量。

使用注意事项:

在提升的PowerShell上运行这些命令(例如,具有管理员权限)。 在每一步之后,为了使您的命令工作,关闭会话并再次打开它。

添加/创建永久环境变量:

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

Machine是一个环境变量目标,将应用于当前和未来的用户,而不是User目标。


修改/改变环境变量:

[Environment]::SetEnvironmentVariable("MyEnvVar", "NewerEnvValue", "Machine")

删除/删除变量:

[Environment]::SetEnvironmentVariable("MyEnvVar", "", "Machine")