57

I'm trying to write a simple PowerShell script to deploy a Visual Studio ASPNET Core 1 project.

Currently, in a batch file i can say

Path=.\node_modules\.bin;%AppData%\npm;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\git

That will modify the path variable for the duration of the session... for the life of me I can't figure out how to do this simple thing in powershell.

Can someone help me translate this into powershell?

TIA!

Rook
  • 5,734
  • 3
  • 34
  • 43
Simon Ordo
  • 1,517
  • 2
  • 14
  • 23
  • 3
    Thanks Simon, this is the first hit on google when searching for "powershell add to path temporarily"! – xpt Jul 29 '20 at 16:50

2 Answers2

99

Option 1: Modify the $env:Path Variable

  1. Append to the Path variable in the current window:

    $env:Path += ";C:\New directory 1;C:\New directory 2"
    
  2. Prefix the Path variable in the current window:

    $env:Path = "C:\New directory 1;C:\New directory 2;" + $env:Path
    
  3. Replace the Path variable in the current window (use with caution!):

    $env:Path = "C:\New directory 1;C:\New directory 2"
    

Option 2: Use the editenv Utility

I wrote a Windows command-line tool called editenv that lets you interactively edit the content of an environment variable. It works from a Windows console (notably, it does not work from the PowerShell ISE):

editenv Path

This can be useful when you want to edit and rearrange the directories in your Path in a more interactive fashion, and it affects only the current window.

Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
  • 8
    If you use += to add to the existing paths, make sure you add a semicolon BEFORE the added path. E.G.$Env:Path += ";C:\New directory 1;C:\New directory 2" – samneric Nov 26 '18 at 21:08
  • 1
    I reordered the information in my answer to avoid confusion. – Bill_Stewart Oct 10 '19 at 17:19
  • 2
    and sometimes you want the new path information first - in which case you can't use += ex. $Env.Path = "C:\New Directory;" + $Env.Path – Jimbugs Mar 02 '20 at 15:13
  • Thanks for the suggestions regarding adding and prefixing - updated answer. – Bill_Stewart Nov 24 '20 at 15:21
6

You can just use $env:Path, but if you're anxious that that isn't explicit enough, you can use System.Environment.SetEnvironmentVariable():

[System.Environment]::SetEnvironmentVariable('Path',$Value,[System.EnvironmentVariableTarget]::Process);

And GetEnvironmentVariable() can explicitly retrieve:

[System.Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Process);
[System.Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine);
[System.Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::User);
Bacon Bits
  • 30,782
  • 5
  • 59
  • 66