2013-07-22 55 views
72

如果我有一個正在運行的Powershell ISE實例,並且我安裝了一些修改PATH的東西,或者我以任何方式在Powershell之外修改它,那麼我需要重新啓動Powershell才能看到更新的PATH變量。重新加載PowerShell中的路徑

有什麼方法可以在Powershell中重新加載路徑而無需重新啓動嗎?

回答

81

只需要拿Rob's comment光:

$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") 
+2

** Yup。** [Rob's comment](https://stackoverflow.com/questions/17794507/reload-the-path-in- powershell#comment25967553_17794885)確實是在搖動Powershell Casbah。 –

+5

應該更容易... – Dyin

+7

如果你使用的是巧克力,並將其加載到你的個人資料中,則有一個更簡單的命令:'refreshenv'。這基本上運行了rob的評論[更詳細的版本](https://github.com/chocolatey/choco/blob/stable/src/chocolatey.resources/helpers/functions/Update-SessionEnvironment.ps1)。 –

59

嘗試獲取機器路徑並將其分配給會話路徑。

$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") 
+30

謝謝你的工作!我也有一個名爲path的用戶環境變量,所以我必須這樣做:[System.Environment] :: GetEnvironmentVariable(「Path」,「Machine」)+「;」 + [System.Environment] :: GetEnvironmentVariable(「Path」,「User」) – rob

0

如果你的路徑包含在會議開始並沒有定義的環境變量,你要擴大這些太

$env:Path = [System.Environment]::ExpandEnvironmentVariables([System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")) 

對我來說,這在安裝NVM後非常有用,該NVM定義並將%NVM_HOME%添加到路徑中

藉此得出的邏輯結論,你可以使用這個遞歸函數來擴大而不是

function Expand-EnvironmentVariablesRecursively($unexpanded) { 
    $previous = '' 
    $expanded = $unexpanded 
    while($previous -ne $expanded) { 
     $previous = $expanded  
     $expanded = [System.Environment]::ExpandEnvironmentVariables($previous) 
    } 
    return $expanded 
} 

然後用

$env:Path = Expand-EnvironmentVariablesRecursively([System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")) 

我已經opened an issue該解決方案從巧克力味加入到refreshenv