Updating PATH environment variable using PowerShell

I am writing a script to configure a fresh Windows installation to fit my workflow. This usually involves installing chocolatey as my package manager and installing programs I need. Along with it, I also need to restore settings for certain apps and update the PATH environment variable.

Until today I've always added paths manually, but it turns out, there's an easier way. Thanks to some googling, I was able to create this script that adds the given dir to PATH environment variable for the current user.

function Add-ToUserPath {
    param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string] 
        $dir
    )

    $dir = (Resolve-Path $dir)

    $path = [Environment]::GetEnvironmentVariable("PATH", [System.EnvironmentVariableTarget]::User)
    if (!($path.Contains($dir))) {
        # backup the current value
        "PATH=$path" | Set-Content -Path "$env:USERPROFILE/path.env"
        # append dir to path
        [Environment]::SetEnvironmentVariable("PATH", $path + ";$dir", [EnvironmentVariableTarget]::User)
        Write-Host "Added $dir to PATH"
        return
    }
    Write-Error "$dir is already in PATH"
}

It expects a path to a directory as the argument:

Add-ToUserPath "$env:USERPROFILE/.bin"

If you want to set the environment variable for all users, change the target [System.EnvironmentVariableTarget] parameter from User to Machine.

Adding the script to PowerShell profile

Pasting and running this code, or importing a file every time we need to update PATH defeats the purpose. We need a way to access it quickly. That's where the PowerShell profile comes into play. It's a file (similar to .bashrc in bash) that runs everytime a PowerShell session starts[1]

Open the profile with an editor.

notepad $PROFILE

Paste the function into this file and save it. When you open a new powershell window, you should be able to use the function.


  1. Unless -NoProfile argument is given ↩︎

Last updated: