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

注意:

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


当前回答

大多数答案都没有涉及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

其他回答

更改实际的环境变量可以通过 使用env:命名空间/驱动器信息。例如,这个 代码将更新path环境变量:

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

让改变永久化

有办法让环境设置永久存在,但是 如果你只从PowerShell中使用它们,它可能 使用Powershell配置文件脚本更好。

每次Powershell的一个新实例启动时,它都会查找特定的脚本文件(称为配置文件),如果它们存在,就执行它们。您可以编辑这些概要文件中的一个来定制您的环境。

要了解这些配置文件脚本在您的计算机中的位置,请键入:

$profile                                     
$profile.AllUsersAllHosts           
$profile.AllUsersCurrentHost        
$profile.CurrentUserAllHosts    
$profile.CurrentUserCurrentHost     

你可以编辑其中一个,例如,输入:

notepad $profile

这设置了当前会话的路径,并提示用户永久添加它:

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

您可以将此函数添加到您的默认配置文件(Microsoft.PowerShell_profile.ps1),通常位于%USERPROFILE%\Documents\WindowsPowerShell。

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

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
 }

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

在@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时,它将以适当的键打开。

就像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函数。