Table of Contents
Refresh Environment Variables in PowerShell without Reopening
In this post, we will show you how to refresh the Path environment variables without closing and reopening the PowerShell session. For example, we’ve a simple PowerShell script:
- Install Oy-My-Posh.
- Wait three seconds.
- Then install a font for Oh-My-Posh.
winget install JanDeDobbeleer.OhMyPosh -s winget
Start-Sleep -Seconds 3
oh-my-posh font install AnonymousPro
As you can see in the below screenshot. After the app is installed, PowerShell need to reload the Path environment variables to know the path of the executable file (oh-my-posh.exe).
PowerShell does not recognize the operable program because it only finds the scripts and executable files in the folders listed in the Path environment variables.
oh-my-posh : The term ‘oh-my-posh’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ oh-my-posh font install AnonymousPro
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (oh-my-posh:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
To fix it, we need to edit out script as follows:
- Install Oy-My-Posh.
- Wait three seconds.
- Update the Path environment variables to include the path of the file oh-my-posh.exe.
- Then install a font for Oh-My-Posh.
winget install JanDeDobbeleer.OhMyPosh -s winget
Start-Sleep -Seconds 3
# Update the $env:Path to the current session
$userpath = [System.Environment]::GetEnvironmentVariable("Path","User")
$machinePath = [System.Environment]::GetEnvironmentVariable("Path","Machine")
$env:Path = $userpath + ";" + $machinePath
oh-my-posh font install AnonymousPro
This time, after the path env is updated in the current PowerShell session. PowerShell knows the path of the executable file then using it to install the font with the last command.
Using refreshenv - Chocolatey
Alternatively, if you’re using Chocolatey as your Windows package manager. You can use its function refreshenv to refresh the path environment variables in the current session.
PS C:\> Get-Command refreshenv
Name : RefreshEnv.cmd
CommandType : Application
Definition : C:\ProgramData\chocolatey\bin\RefreshEnv.cmd
Extension : .cmd
Path : C:\ProgramData\chocolatey\bin\RefreshEnv.cmd
irm community.chocolatey.org/install.ps1 | iex
Install the Chocolatey in the target computer then you need to add the refreshenv cmdlet into the PowerShell script before installing the font.
winget install JanDeDobbeleer.OhMyPosh -s winget
Start-Sleep -Seconds 3
RefreshEnv
oh-my-posh font install AnonymousPro
Not a reader? Watch this related video tutorial: