Windows: How to add a program to the system’s path environmental variable from the command line

command-line-interfaceenvironment-variablespathwindowswindows-command-prompt

I'm looking to permanently add a directory to the %PATH% environmental available on a large number of Windows machines. Is there any way to do this from a command line (cmd) so I can script up a solution, rather than having to use GUI on dozens of servers.

How can I go about accomplishing this?

Best Answer

By far, the easiest way to go about this is through the use of the setx command, which is included in Windows 7/Server 2008 and up, or as part of the Windows Server 2003 Resource Kit for XP and Server 2003 systems.

You can use the setx command to either specify an entirely new set of directories in the %PATH% variable, or append a value, using a little extra logic. Say I wanted to add the directory at C:\stuff to the %PATH%. I would do so as below:

setx PATH "%PATH%,C:\stuff" /M

This appends ,C:\stuff to the current path by overwriting the existing path with its current value, followed by ,C:\stuff. The path environmental variable is comma delimited. The /M switch makes the change in the HKLM (system-wide) registry hive, rather than the HKCU (the current user) registry hive.

You could throw this into a logon/startup script, or use the /s switch to specify a remote server as the target, and make the changes from your workstation. For example, the below would add the stuff directory to the path on myserver.mydomain.com, with the credentials for the mydomainadmin user.

setx /s myserver.mydomain.com /u mydomain\mydomainadmin /p mypassword PATH "%PATH%,C:\stuff" /M

The usual qualifications apply, mainly that changing a global environmental variable will only affect user sessions on their next logon, and will only apply to applications when they next check, which is usually at startup, so the easiest way to get this to apply to everything is to reboot the server, though if you know specifically what users or services need the change, you can take less disruptive measures to get the change applied.