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

注意:

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


当前回答

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

其他回答

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

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。

如果在PowerShell会话期间,您需要查看或临时修改PATH环境变量,您可以键入以下命令之一:

$env:Path                             # shows the actual content
$env:Path = 'C:\foo;' + $env:Path     # attach to the beginning
$env:Path += ';C:\foo'                # attach to the end

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

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

如果你需要动态地为会话设置变量名,那么使用:

New-Item env:\$key -Value $value -Force | Out-Null