PowerShell:如何删除Path环境变量中的路径

时间:2016-08-18 05:12:35

标签: powershell

我使用“setx”为PATH环境变量添加新路径。如何查看是否可以从PATH环境变量中删除新添加的路径?

3 个答案:

答案 0 :(得分:13)

从%PATH%中删除特定值需要您获取变量,修改变量并将其放回。

例如。

# Get it
$path = [System.Environment]::GetEnvironmentVariable(
    'PATH',
    'Machine'
)
# Remove unwanted elements
$path = ($path.Split(';') | Where-Object { $_ -ne 'ValueToRemove' }) -join ';'
# Set it
[System.Environment]::SetEnvironmentVariable(
    'PATH',
    $path,
    'Machine'
)

答案 1 :(得分:0)

克里斯的回答在重启后不会持续存在。为了在重新启动后工作,您需要修改PATH的注册表位置。以下是从路径中删除项目和添加项目的功能示例:

# Modify PATH variable
function changePath ($action, $addendum) {
    $regLocation = 
"Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment"
    $path = (Get-ItemProperty -Path $regLocation -Name PATH).path

    # Add an item to PATH
    if ($action -eq "add") {
        $path = "$path;$addendum"
        Set-ItemProperty -Path $regLocation -Name PATH -Value $path
    }

    # Remove an item from PATH
    if ($action -eq "remove") {
        $path = ($path.Split(';') | Where-Object { $_ -ne "$addendum" }) -join ';'
        Set-ItemProperty -Path $regLocation -Name PATH -Value $path
    }
}

# Add an item to your path
changePath "add" "C:\example"

# Remove an item from your path
changePath "remove" "C:\example"

答案 2 :(得分:0)

我想对此帖子进行更新。仅更改$Env:Path或使用[System.Environment]::SetEnvironmentVariable()不会永久更改Rich先前的帖子中的path变量(也许Windows从原始帖子起就更改了)。它只会在Powershell中对该会话进行更改。退出并重新启动Powershell之后,路径将恢复原状。为了在Powershell中永久更改它,您必须更改注册表中的值。

这是修改注册表的另一种方法(可以修改以适合新的所需路径)。

#Path of the directory you want to add
$newPath = 'C:\folder\another folder\etc'

#Gets the original value from the registry
$oldPath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path

#Sets the registry to the new value. NOTE: You have to get the old path, otherwise if you just use set-itemproperty with $newPath, it sets it just to that new path, erasing the previous path
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value "$oldPath$newPath;"
#Semi-colon at the end is to keep the consistency of the path variable
#You can double-check it worked using the Environment Variables GUI

此信息也可以在以下外部网站上找到: https://codingbee.net/powershell/powershell-make-a-permanent-change-to-the-path-environment-variable