├── .github ├── FUNDING.yml └── README.md ├── .gitignore ├── LICENSE └── Refresh-EnvironmentVariables.ps1 /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [asheroto] 2 | ko_fi: asheroto 3 | -------------------------------------------------------------------------------- /.github/README.md: -------------------------------------------------------------------------------- 1 | ![Refresh-EnvironmentVariables](https://github.com/asheroto/Refresh-EnvironmentVariables/assets/49938263/baedbab3-f1c3-4965-9b5e-a9674781093a) 2 | 3 | [![GitHub Release Date - Published_At](https://img.shields.io/github/release-date/asheroto/Refresh-EnvironmentVariables)](https://github.com/asheroto/Refresh-EnvironmentVariables/releases) 4 | [![GitHub Downloads - All Releases](https://img.shields.io/github/downloads/asheroto/Refresh-EnvironmentVariables/total)](https://github.com/asheroto/Refresh-EnvironmentVariables/releases) 5 | [![GitHub Sponsor](https://img.shields.io/github/sponsors/asheroto?label=Sponsor&logo=GitHub)](https://github.com/sponsors/asheroto) 6 | Ko-Fi Button 7 | 8 | # Refresh-EnvironmentVariables 9 | 10 | Refreshes/reloads the environment variables in the current PowerShell session. 11 | 12 | No need to close and reopen PowerShell. 13 | 14 | ## Background 15 | 16 | This script is derived from [Chocolatey's helper functions](https://github.com/chocolatey/choco/tree/master/src/chocolatey.resources/helpers/functions). The functions have been combined them into one script and some additional functionality has been added. Chocolatey is not required to run `Rrefresh-EnvironmentVariables`. 17 | 18 | Per the [Apache 2.0 license](https://www.apache.org/licenses/LICENSE-2.0.html), the original license is included in the script along with the original author attribution, copyright, and changes. To keep things simple, the same license is used in this script. [More info](https://snyk.io/learn/apache-license/) 19 | ## Setup 20 | 21 | ### Method 1 - PowerShell Gallery 22 | 23 | Please install the latest version using `Install-Script` or the `PS1` file from [Releases](https://github.com/asheroto/Refresh-EnvironmentVariables/releases). The version on the repo itself may be under development and not work as expected. 24 | 25 | Open PowerShell as Administrator and type 26 | 27 | ```powershell 28 | Install-Script Refresh-EnvironmentVariables -Force 29 | ``` 30 | 31 | Follow the prompts to complete the installation (you can tap `A` to accept all prompts or `Y` to select them individually. 32 | 33 | **Note:** `-Force` is optional but recommended, as it will force the script to update if it is outdated. 34 | 35 | The script is published on [PowerShell Gallery](https://www.powershellgallery.com/packages/Refresh-EnvironmentVariables) under `Refresh-EnvironmentVariables`. 36 | 37 | ### Tip - How to trust PSGallery 38 | 39 | If you want to trust PSGallery so you aren't prompted each time you run this command, or if you're scripting this and want to ensure the script isn't interrupted the first time it runs... 40 | 41 | ```powershell 42 | Install-PackageProvider -Name "NuGet" -Force 43 | Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted 44 | ``` 45 | 46 | ### Method 2 - Download Locally and Run 47 | 48 | - Download the latest [Refresh-EnvironmentVariables.ps1](https://github.com/asheroto/Refresh-EnvironmentVariables/releases/latest/download/Refresh-EnvironmentVariables.ps1) from [Releases](https://github.com/asheroto/Refresh-EnvironmentVariables/releases) 49 | - Run the script with `.\Refresh-EnvironmentVariables.ps1` 50 | 51 | ## Usage 52 | 53 | In PowerShell, type 54 | 55 | ```powershell 56 | Refresh-EnvironmentVariables 57 | ``` 58 | 59 | ## Alias 60 | 61 | If you want to add an alias to the command, you can add the following to your PowerShell profile: 62 | 63 | ```powershell 64 | New-Alias -Name RefreshEnv -Value Refresh-EnvironmentVariables 65 | ``` 66 | 67 | Aliases take precedence over functions, cmdlets, and exe/bat/cmd files, so you can type `RefreshEnv` instead of `Refresh-EnvironmentVariables`. The reason we did not make this the default is that to avoid naming conflicts with Chocolatey's `refreshenv` cmd script. 68 | 69 | ## Parameters 70 | 71 | No parameters are required to run the script, but there are some optional parameters to use if needed. 72 | 73 | | Parameter | Required | Description | 74 | | ----------------- | -------- | ------------------------------------------------------------------------------------------- | 75 | | `-CheckForUpdate` | No | Checks if there is an update available for the script. | 76 | | `-Version` | No | Displays the version of the script. | 77 | | `-Help` | No | Displays the full help information for the script. | 78 | 79 | ## Contributing 80 | 81 | If you're like to help develop this project: fork the repo, make your changes, and submit a pull request. 😊 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | UPDATE-NOTES 2 | dist/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2023] [asheroto / Chocolatey Software, Inc.] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /Refresh-EnvironmentVariables.ps1: -------------------------------------------------------------------------------- 1 | <#PSScriptInfo 2 | 3 | .VERSION 1.0.2 4 | 5 | .GUID 9ff8b18d-cc46-449e-81f1-bbdacc3f41b4 6 | 7 | .AUTHOR asherto 8 | 9 | .COMPANYNAME asheroto 10 | 11 | .TAGS PowerShell Windows refresh reload path env environment variable variables update current 12 | 13 | .PROJECTURI https://github.com/asheroto/Refresh-EnvironmentVariables 14 | 15 | .RELEASENOTES 16 | [Version 0.0.1] - Initial Release. 17 | [Version 1.0.0] - Total rework of script, implementing Chocolatey's Update-SessionEnvironment function into one single script. 18 | [Version 1.0.1] - Rename to Refresh-EnvironmentVariables to avoid naming conflicts with Chocolatey's RefreshEnv.cmd. 19 | [Version 1.0.2] - Fix bug with CheckForUpdate. 20 | 21 | #> 22 | 23 | <# 24 | .SYNOPSIS 25 | Refreshes the environment variables in the current PowerShell session. 26 | .DESCRIPTION 27 | Refreshes the environment variables in the current PowerShell session. 28 | .EXAMPLE 29 | Refresh-EnvironmentVariables 30 | .PARAMETER CheckForUpdate 31 | Checks if there is an update available for the script. 32 | .PARAMETER Version 33 | Displays the version of the script. 34 | .PARAMETER Help 35 | Displays the full help information for the script. 36 | .NOTES 37 | Version : 1.0.2 38 | Created by : asheroto 39 | .LINK 40 | Project Site: https://github.com/asheroto/Refresh-EnvironmentVariables 41 | #> 42 | [CmdletBinding()] 43 | param ( 44 | [switch]$Version, 45 | [switch]$Help, 46 | [switch]$CheckForUpdate 47 | ) 48 | 49 | # Derived from the original work by Chocolatey Software, used in accordance with license 50 | # Copyright © 2017 - 2021 Chocolatey Software, Inc. 51 | 52 | # Changes made: 53 | # - Extracted the functions from the original script for use in Refresh-EnvironmentVariables.ps1 54 | # - Removed Write-FunctionCallLogMessage from Update-SessionEnvironment as it only applies to Chocolatey 55 | # - Added custom functions 56 | 57 | # Original license, included per the terms of the Apache 2.0 license: 58 | # Licensed under the Apache License, Version 2.0 (the "License"); 59 | # you may not use this file except in compliance with the License. 60 | # You may obtain a copy of the License at 61 | # 62 | # http://www.apache.org/licenses/LICENSE-2.0 63 | # 64 | # Unless required by applicable law or agreed to in writing, software 65 | # distributed under the License is distributed on an "AS IS" BASIS, 66 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 67 | # See the License for the specific language governing permissions and 68 | # limitations under the License. 69 | 70 | # Version 71 | $CurrentVersion = '1.0.2' 72 | $RepoOwner = 'asheroto' 73 | $RepoName = 'Refresh-EnvironmentVariables' 74 | $PowerShellGalleryName = 'Refresh-EnvironmentVariables' 75 | 76 | # Versions 77 | $ProgressPreference = 'SilentlyContinue' # Suppress progress bar (makes downloading super fast) 78 | $ConfirmPreference = 'None' # Suppress confirmation prompts 79 | 80 | # Display version if -Version is specified 81 | if ($Version.IsPresent) { 82 | $CurrentVersion 83 | exit 0 84 | } 85 | 86 | # Display full help if -Help is specified 87 | if ($Help) { 88 | Get-Help -Name $MyInvocation.MyCommand.Source -Full 89 | exit 0 90 | } 91 | 92 | function Get-GitHubRelease { 93 | <# 94 | .SYNOPSIS 95 | Fetches the latest release information of a GitHub repository. 96 | 97 | .DESCRIPTION 98 | This function uses the GitHub API to get information about the latest release of a specified repository, including its version and the date it was published. 99 | 100 | .PARAMETER Owner 101 | The GitHub username of the repository owner. 102 | 103 | .PARAMETER Repo 104 | The name of the repository. 105 | 106 | .EXAMPLE 107 | Get-GitHubRelease -Owner "asheroto" -Repo "winget-install" 108 | This command retrieves the latest release version and published datetime of the winget-install repository owned by asheroto. 109 | #> 110 | [CmdletBinding()] 111 | param ( 112 | [string]$Owner, 113 | [string]$Repo 114 | ) 115 | try { 116 | $url = "https://api.github.com/repos/$Owner/$Repo/releases/latest" 117 | $response = Invoke-RestMethod -Uri $url -ErrorAction Stop 118 | 119 | $latestVersion = $response.tag_name 120 | $publishedAt = $response.published_at 121 | 122 | # Convert UTC time string to local time 123 | $UtcDateTime = [DateTime]::Parse($publishedAt, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::RoundtripKind) 124 | $PublishedLocalDateTime = $UtcDateTime.ToLocalTime() 125 | 126 | [PSCustomObject]@{ 127 | LatestVersion = $latestVersion 128 | PublishedDateTime = $PublishedLocalDateTime 129 | } 130 | } catch { 131 | Write-Error "Unable to check for updates.`nError: $_" 132 | exit 1 133 | } 134 | } 135 | 136 | function CheckForUpdate { 137 | param ( 138 | [string]$RepoOwner, 139 | [string]$RepoName, 140 | [version]$CurrentVersion, 141 | [string]$PowerShellGalleryName 142 | ) 143 | 144 | $Data = Get-GitHubRelease -Owner $RepoOwner -Repo $RepoName 145 | 146 | if ($Data.LatestVersion -gt $CurrentVersion) { 147 | Write-Output "`nA new version of $RepoName is available.`n" 148 | Write-Output "Current version: $CurrentVersion." 149 | Write-Output "Latest version: $($Data.LatestVersion)." 150 | Write-Output "Published at: $($Data.PublishedDateTime).`n" 151 | Write-Output "You can download the latest version from https://github.com/$RepoOwner/$RepoName/releases`n" 152 | if ($PowerShellGalleryName) { 153 | Write-Output "Or you can run the following command to update:" 154 | Write-Output "Install-Script $PowerShellGalleryName -Force`n" 155 | } 156 | } else { 157 | Write-Output "`n$RepoName is up to date.`n" 158 | Write-Output "Current version: $CurrentVersion." 159 | Write-Output "Latest version: $($Data.LatestVersion)." 160 | Write-Output "Published at: $($Data.PublishedDateTime)." 161 | Write-Output "`nRepository: https://github.com/$RepoOwner/$RepoName/releases`n" 162 | } 163 | exit 0 164 | } 165 | 166 | # Check for updates if -CheckForUpdate is specified 167 | if ($CheckForUpdate) { 168 | CheckForUpdate -RepoOwner $RepoOwner -RepoName $RepoName -CurrentVersion $CurrentVersion -PowerShellGalleryName $PowerShellGalleryName 169 | } 170 | 171 | function Get-EnvironmentVariable { 172 | <# 173 | .SYNOPSIS 174 | Gets an Environment Variable. 175 | 176 | .DESCRIPTION 177 | This will will get an environment variable based on the variable name 178 | and scope while accounting whether to expand the variable or not 179 | (e.g.: `%TEMP%`-> `C:\User\Username\AppData\Local\Temp`). 180 | 181 | .NOTES 182 | This helper reduces the number of lines one would have to write to get 183 | environment variables, mainly when not expanding the variables is a 184 | must. 185 | 186 | .PARAMETER Name 187 | The environment variable you want to get the value from. 188 | 189 | .PARAMETER Scope 190 | The environment variable target scope. This is `Process`, `User`, or 191 | `Machine`. 192 | 193 | .PARAMETER PreserveVariables 194 | A switch parameter stating whether you want to expand the variables or 195 | not. Defaults to false. 196 | 197 | .PARAMETER IgnoredArguments 198 | Allows splatting with arguments that do not apply. Do not use directly. 199 | 200 | .EXAMPLE 201 | Get-EnvironmentVariable -Name 'TEMP' -Scope User -PreserveVariables 202 | 203 | .EXAMPLE 204 | Get-EnvironmentVariable -Name 'PATH' -Scope Machine 205 | 206 | .LINK 207 | Get-EnvironmentVariableNames 208 | 209 | .LINK 210 | Set-EnvironmentVariable 211 | #> 212 | [CmdletBinding()] 213 | [OutputType([string])] 214 | param( 215 | [Parameter(Mandatory = $true)][string] $Name, 216 | [Parameter(Mandatory = $true)][System.EnvironmentVariableTarget] $Scope, 217 | [Parameter(Mandatory = $false)][switch] $PreserveVariables = $false, 218 | [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments 219 | ) 220 | 221 | # Do not log function call, it may expose variable names 222 | ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch 223 | 224 | [string] $MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"; 225 | [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($MACHINE_ENVIRONMENT_REGISTRY_KEY_NAME) 226 | if ($Scope -eq [System.EnvironmentVariableTarget]::User) { 227 | [string] $USER_ENVIRONMENT_REGISTRY_KEY_NAME = "Environment"; 228 | [Microsoft.Win32.RegistryKey] $win32RegistryKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($USER_ENVIRONMENT_REGISTRY_KEY_NAME) 229 | } elseif ($Scope -eq [System.EnvironmentVariableTarget]::Process) { 230 | return [Environment]::GetEnvironmentVariable($Name, $Scope) 231 | } 232 | 233 | [Microsoft.Win32.RegistryValueOptions] $registryValueOptions = [Microsoft.Win32.RegistryValueOptions]::None 234 | 235 | if ($PreserveVariables) { 236 | Write-Verbose "Choosing not to expand environment names" 237 | $registryValueOptions = [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames 238 | } 239 | 240 | [string] $environmentVariableValue = [string]::Empty 241 | 242 | try { 243 | #Write-Verbose "Getting environment variable $Name" 244 | if ($win32RegistryKey -ne $null) { 245 | # Some versions of Windows do not have HKCU:\Environment 246 | $environmentVariableValue = $win32RegistryKey.GetValue($Name, [string]::Empty, $registryValueOptions) 247 | } 248 | } catch { 249 | Write-Debug "Unable to retrieve the $Name environment variable. Details: $_" 250 | } finally { 251 | if ($win32RegistryKey -ne $null) { 252 | $win32RegistryKey.Close() 253 | } 254 | } 255 | 256 | if ($environmentVariableValue -eq $null -or $environmentVariableValue -eq '') { 257 | $environmentVariableValue = [Environment]::GetEnvironmentVariable($Name, $Scope) 258 | } 259 | 260 | return $environmentVariableValue 261 | } 262 | 263 | function Get-EnvironmentVariableNames([System.EnvironmentVariableTarget] $Scope) { 264 | <# 265 | .SYNOPSIS 266 | Gets all environment variable names. 267 | 268 | .DESCRIPTION 269 | Provides a list of environment variable names based on the scope. This 270 | can be used to loop through the list and generate names. 271 | 272 | .NOTES 273 | Process dumps the current environment variable names in memory / 274 | session. The other scopes refer to the registry values. 275 | 276 | .INPUTS 277 | None 278 | 279 | .OUTPUTS 280 | A list of environment variables names. 281 | 282 | .PARAMETER Scope 283 | The environment variable target scope. This is `Process`, `User`, or 284 | `Machine`. 285 | 286 | .EXAMPLE 287 | Get-EnvironmentVariableNames -Scope Machine 288 | 289 | .LINK 290 | Get-EnvironmentVariable 291 | 292 | .LINK 293 | Set-EnvironmentVariable 294 | #> 295 | 296 | # Do not log function call 297 | 298 | # HKCU:\Environment may not exist in all Windows OSes (such as Server Core). 299 | switch ($Scope) { 300 | 'User' { 301 | Get-Item 'HKCU:\Environment' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Property 302 | } 303 | 'Machine' { 304 | Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' | Select-Object -ExpandProperty Property 305 | } 306 | 'Process' { 307 | Get-ChildItem Env:\ | Select-Object -ExpandProperty Key 308 | } 309 | default { 310 | throw "Unsupported environment scope: $Scope" 311 | } 312 | } 313 | } 314 | 315 | function Update-SessionEnvironment { 316 | <# 317 | .SYNOPSIS 318 | Updates the environment variables of the current powershell session with 319 | any environment variable changes that may have occurred during a 320 | Chocolatey package install. 321 | 322 | .DESCRIPTION 323 | When Chocolatey installs a package, the package author may add or change 324 | certain environment variables that will affect how the application runs 325 | or how it is accessed. Often, these changes are not visible to the 326 | current PowerShell session. This means the user needs to open a new 327 | PowerShell session before these settings take effect which can render 328 | the installed application nonfunctional until that time. 329 | 330 | Use the Update-SessionEnvironment command to refresh the current 331 | PowerShell session with all environment settings possibly performed by 332 | Chocolatey package installs. 333 | 334 | .NOTES 335 | This method is also added to the user's PowerShell profile as 336 | `refreshenv`. When called as `refreshenv`, the method will provide 337 | additional output. 338 | 339 | Preserves `PSModulePath` as set by the process. 340 | 341 | .INPUTS 342 | None 343 | 344 | .OUTPUTS 345 | None 346 | #> 347 | 348 | $userName = $env:USERNAME 349 | $architecture = $env:PROCESSOR_ARCHITECTURE 350 | $psModulePath = $env:PSModulePath 351 | 352 | #ordering is important here, $user should override $machine... 353 | $ScopeList = 'Process', 'Machine' 354 | if ('SYSTEM', "${env:COMPUTERNAME}`$" -notcontains $userName) { 355 | # but only if not running as the SYSTEM/machine in which case user can be ignored. 356 | $ScopeList += 'User' 357 | } 358 | 359 | foreach ($Scope in $ScopeList) { 360 | Get-EnvironmentVariableNames -Scope $Scope | 361 | ForEach-Object { 362 | Set-Item "Env:$_" -Value (Get-EnvironmentVariable -Scope $Scope -Name $_) 363 | } 364 | } 365 | 366 | #Path gets special treatment b/c it munges the two together 367 | $paths = 'Machine', 'User' | 368 | ForEach-Object { 369 | (Get-EnvironmentVariable -Name 'PATH' -Scope $_) -split ';' 370 | } | 371 | Select-Object -Unique 372 | $Env:PATH = $paths -join ';' 373 | 374 | # PSModulePath is almost always updated by process, so we want to preserve it. 375 | $env:PSModulePath = $psModulePath 376 | 377 | # reset user and architecture 378 | if ($userName) { 379 | $env:USERNAME = $userName; 380 | } 381 | if ($architecture) { 382 | $env:PROCESSOR_ARCHITECTURE = $architecture; 383 | } 384 | } 385 | 386 | # Output 387 | Write-Output "Refreshing environment variables..." 388 | 389 | # Call the function to update the session environment 390 | Update-SessionEnvironment 391 | 392 | # Output 393 | Write-Output "Finished" --------------------------------------------------------------------------------