Где прописать path в windows

Все способы:

  • Переменные среды Windows
    • Переменные PATH и PATHEXT
    • Создание переменных среды
    • Заключение
  • Вопросы и ответы: 6

Переменная среды (переменная окружения) – это короткая ссылка на какой-либо объект в системе. С помощью таких сокращений, например, можно создавать универсальные пути для приложений, которые будут работать на любых ПК, независимо от имен пользователей и других параметров.

Переменные среды Windows

Получить информацию о существующих переменных можно в свойствах системы. Для этого кликаем по ярлыку Компьютера на рабочем столе правой кнопкой мыши и выбираем соответствующий пункт.

Переход к свойствам операционной системы с рабочего стола Windows 10

Переходим в «Дополнительные параметры».

Переход к дополнительным параметрам системы в ОС Windows 10

В открывшемся окне с вкладкой «Дополнительно» нажимаем кнопку, указанную на скриншоте ниже.

Переход к обзору переменных среды в ОС Windows 10

Здесь мы видим два блока. Первый содержит пользовательские переменные, а второй системные.

Раздел настройки переменных среды в Windows 10

Если требуется просмотреть весь перечень, запускаем «Командную строку» от имени администратора и выполняем команду (вводим и нажимаем ENTER).

set > %homepath%\desktop\set.txt

Создание текстового документа со списком переменных среды из Командной строки Windows 10

Подробнее: Как открыть «Командную строку» в Windows 10

На рабочем столе появится файл с названием «set.txt», в котором будут указаны все переменные окружения, имеющиеся в системе.

Текстовый документ со списком переменных среды Windows 10

Все их можно использовать в консоли или скриптах для запуска программ или поиска объектов, заключив имя в знаки процента. Например, в команде выше вместо пути

C:\Users\Имя_пользователя

мы использовали

%homepath%

Примечание: регистр при написании переменных не важен. Path=path=PATH

Переменные PATH и PATHEXT

Если с обычными переменными все понятно (одна ссылка – одно значение), то эти две стоят особняком. При детальном рассмотрении видно, что они ссылаются сразу на несколько объектов. Давайте разберемся, как это работает.

Переменные среды PATH и PATHEXT в Windows 10

«PATH» позволяет запускать исполняемые файлы и скрипты, «лежащие» в определенных каталогах, без указания их точного местоположения. Например, если ввести в «Командную строку»

explorer.exe

система осуществит поиск по папкам, указанным в значении переменной, найдет и запустит соответствующую программу. Этим можно воспользоваться в своих целях двумя способами:

  • Поместить необходимый файл в одну из указанных директорий. Полный список можно получить, выделив переменную и нажав «Изменить».
    Переход к изменению переменной среды PATH в ОС Windows 10

  • Создать свою папку в любом месте и прописать путь к ней. Для этого (после создания директории на диске) жмем «Создать», вводим адрес и ОК.

    Добавление значения переменной PATH в Windows 10

    %SYSTEMROOT% определяет путь до папки «Windows» независимо от буквы диска.

    Затем нажимаем ОК в окнах «Переменные среды» и «Свойства системы».

    Применение настроек переменных окружения в Windows 10

Для применения настроек, возможно, придется перезапустить «Проводник». Сделать это быстро можно так:

Открываем «Командную строку» и пишем команду

taskkill /F /IM explorer.exe

Завершение работы Проводника из Командной строки в Windows 10

Все папки и «Панель задач» исчезнут. Далее снова запускаем «Проводник».

explorer

Перезапуск Проводника из Командной строки в Windows 10

Еще один момент: если вы работали с «Командной строкой», ее также следует перезапустить, то есть консоль не будет «знать», что настройки изменились. Это же касается и фреймворков, в которых вы отлаживаете свой код. Также можно перезагрузить компьютер или выйти и снова зайти в систему.

Теперь все файлы, помещенные в «C:\Script» можно будет открывать (запускать), введя только их название.

Запуск файла с помощью переменной среды PATH в Windows 10

«PATHEXT», в свою очередь, дает возможность не указывать даже расширение файла, если оно прописано в ее значениях.

Значения переменной среды PATHEXT в Windows 10

Принцип работы следующий: система перебирает расширения по очереди, пока не будет найден соответствующий объект, причем делает это в директориях, указанных в «PATH».

Запуск приложения с помощью переменной PATHEXT в Windows 10

Создание переменных среды

Создаются переменные просто:

  1. Нажимаем кнопку «Создать». Сделать это можно как в пользовательском разделе, так и в системном.
    Переход к созданию переменной среды в Windows 10

  2. Вводим имя, например, «desktop». Обратите внимание на то, чтобы такое название еще не было использовано (просмотрите списки).

    Присвоение имени новой переменной среды в Windows 10

  3. В поле «Значение» указываем путь до папки «Рабочий стол».

    C:\Users\Имя_пользователя\Desktop

    Присвоение значения новой переменной среды в Windows 10

  4. Нажимаем ОК. Повторяем это действие во всех открытых окнах (см. выше).

    Применение настроек при создании новой переменной среды в Windows 10

  5. Перезапускаем «Проводник» и консоль или целиком систему.
  6. Готово, новая переменная создана, увидеть ее можно в соответствующем списке.

    Расположение новой пользовательской переменной среды в списке в Windows 10

Для примера переделаем команду, которую мы использовали для получения списка (самая первая в статье). Теперь нам вместо

set > %homepath%\desktop\set.txt

потребуется ввести только

set > %desktop%\set.txt

Заключение

Использование переменных окружения позволяет значительно сэкономить время при написании скриптов или взаимодействии с системной консолью. Еще одним плюсом является оптимизация создаваемого кода. Имейте в виду, что созданные вами переменные отсутствуют на других компьютерах, и сценарии (скрипты, приложения) с их использованием работать не будут, поэтому перед тем, как передавать файлы другому пользователю, необходимо уведомить его об этом и предложить создать соответствующий элемент в своей системе.

Наша группа в TelegramПолезные советы и помощь

Sometimes we need to tell Windows where to look for a particular executable file or script. Windows provides a means to do this through the Path Environment Variable. The Path Environment Variable essentially provides the OS with a list of directories to look in for a particular .exe or file when the simple name of the file is entered at the command prompt.

For example, the Notepad.exe application resides in the C:\Windows\system32 directory. However, if we wish to open the Notepad application via the Windows Command Line, we need only type:

Opening Notepad.exe From the Windows Command Line:
C:\Users\John> notepad

This works because the Path variable on Windows by default contains a list of directories where application files and scripts are likely to be located. Each directory in the list is separated by a semi-colon.

Similarly, there is another environment variable, PATHEXT which specifies a list of file extensions which might be found when searching for the proper file within the paths in the Path variable. This is why we are able to type simply “Notepad” at the command prompt, instead of Notepad.exe.

Windows will first search the current directory (where the command prompt is a the time the command is executed) to find a name matching the one typed into the terminal, and then search the directories in the Path variable in order, beginning with the most likely locations, and continue until either a matching file name is located, or else return the “… is not recognized blah blah” message at the terminal.

Once a file with a matching name is located, Windows attempts to match the file extension (if one is present), again in the order specified in the PATHEXT variable. If a match is found, the file is processed accordingly.

There are both User-specific and machine-level PATH variables. Machine Path variables are available globally across the machine, and can only be modified by administrators.  User Environment variables can be modified by both administrators, and the user with which the current profile is associated.

Adding a Directory to the User Path Variable from the Command Line

Any user can modify their own PATH variable from the Command Line (unless they have been specifically denied this ability by an administrator).

For example, when we wish to use SQLite from the Windows Command Line, we download the SQLite binaries, and place them in the directory of choice. However, in order to use the SQLite Command Line application without either navigating directly to the folder in which we placed it, or entering the  full file path into our Windows Command Line, we need to add the directory containing the SQLite.exe to our User or System PATH environment variable.

Let’s say a user has downloaded the sqlite3.dll and sqlite3.exe binaries and located them in the directory C:\SQLite.

Now, in order to invoke the sqlite3.exe from the command line, we need to add the C:\SQLite directory to our PATH environment variable. We can do this from the command line by using the setx command:

The setx Command – Syntax:
C:\Users\John> setx "%path%;C:\SQLite"

When we modify environment variables using setx, the changes are not available in the current Console session – in other words, in order to see our changes, we need to exit, and open a new Console window. Then, we can use the following technique:

We can examine the contents of the PATH variable by typing:

Output PATH Variable to the Console:
C:\Users\John> echo %PATH%

Which gives the output:

Results of Echo %PATH% Command:
C:\Users\John>echo %PATH%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind
owsPowerShell\v1.0\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance
Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\
Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\1
10\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\Manage
mentStudio\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Priv
ateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Prog
ram Files (x86)\Common Files\Acronis\SnapAPI\;C:\Program Files (x86)\Windows Liv
e\Shared;C:\Program Files\Calibre2\;C:\Program Files\Microsoft\Web Platform Inst
aller\;C:\Users\John\AppData\Roaming\npm;C:\Program Files (x86)\nodejs\;C:\Progr
am Files (x86)\Microsoft SDKs\Windows Azure\CLI\wbin;C:\Program Files (x86)\GtkS
harp\2.12\bin;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\SQLite

We can see here that C:\SQLite has now been added to the paths available to the current user.

Adding a Directory to the System Path Variable from the Command Line

In the previous section, we used the setx command to add a directory to the current user’s Path variable. Sometimes, we want to make variables available at the system, or machine level. In that case, we use the same setx command in conjunction with the /m flag. However, we need to run the Command Terminal as Administrator for this to work:

Add a Directory the the System PATH Variable Using the /m Flag:
C:\Users\John> setx /m path "%path%;C:\SQLite"

Adding a Directory to the Path Variable from the GUI

Or, we can do this using the GUI by navigating to Control Panel => All Control Panel Items => System, and then selecting the “Advanced System Settings” link:

Locate Advanced System Settings in Control Panels:

Control PanelAll Control Panel ItemsSystem

Then locate the “Environment Variables” button:

Open Environment Variables:

System Properties

Opening Environment Variables, we see the following:

Editing Environment Variables:

Environment Variables

Notice in the image above, there are two sections, User Variables for<Current User>, and System Variables.

Also note, there is not currently a Path variable for me, the current user. We will need to add one, and then add our new path to it:

Adding a User Path Variable in the Windows GUI:

add-path-variable

Once we hit OK, We see we have the single item added to our user path variable.

Added Path Variable to User Environment Variables:

New Environment Variables

For some reason, this works differently than when we do this from the Command Line, when we use the setx command from the terminal, the entirety of the system path variable is copied into the user path variable, including the new entry.

If we have Administrator permissions on our machine, we can do the same for the System PATH variable if we so choose.

Removing Directories from the PATH Variable

In some cases, we may need to remove a directory from our PATH variable. In these cases it is recommended to use the GUI, or edit the registry. It’s easiest to simply open the GUI, copy the contents of the PATH variable (either the User Path or the System Path) to a text editor, and remove the entries you want to delete. Then paste the remaining text back into the Edit Path window, and save.

Additional Resources and Items of Interest

  • Installing and Using SQLite on Windows
  • Getting Started with Git for the Windows Developer (Part I)
  • Basic Git Command Line Reference for Windows Users
  • Git: Interactively Stage Portions of a Single Changed File for Commit Using git add -p

Работа с фронтендом сейчас немыслима без использования консоли (командной строки): набираем какую-либо команду с аргументами — получаем результат. Ну и для некоторых операций консоль дает выигрыш по скорости в сравнении с GUI (сравните создание файловой структуры из GUI с командой mkdir -p project/{js,fonts,scss}).

Зачем это всё

Хочется набирать в консоли subl . для открытия текущей директории как папки проекта или subl filename.html для открытия файла в ST3. При этом не хочется блокировать возможность работы с консолью, как в случае с алиасом.

PATH — это системная переменная, содержащая список директорий, в которых ОС будет искать исполняемый файл при вызове команды из консоли.

В Windows 10 можно добраться до настройки PATH так: Этот компьютер → Свойства → Дополнительные параметры системы → Дополнительно → Переменные среды. Или вызовом «Изменение переменных среды текущего пользователя» в результатах поиска.

В окошке «Переменные среды» в блоке «Переменные среды пользователя %USERNAME%» находим строку PATH, выделяем кликом, жмем кнопку «Изменить…» и в появившемся окошке нажимаем «СОздать» для добавления ещё одного элемента. В самом элементе нужно вписать путь к папке Sublime Text (путь к файлу subl.exe, который должен лежать в папке программы). В моем случае получилось так:

c:\Program Files\Sublime Text 3\

После перезапуска консоли можно наслаждаться командой subl.

Last Updated on 2024-10-11

Understanding and managing environment variables through the environment variable dialog is a fundamental skill for any user or developer in the intricate landscape of computer systems.

At the heart of this crucial system configuration lies the Windows PATH, which determines how your operating system discovers and executes various programs.

Whether you’re a seasoned developer, a tech enthusiast, or a curious user eager to enhance your system skills—be it on personal computers or Windows server systems—this blog is tailored to provide invaluable insights and actionable tips on setting the Windows Path and managing environment variables effectively.

Join us on a comprehensive journey where we unravel the complexities surrounding these critical elements, empowering you to navigate and customize your computing environment with confidence.

What is Windows PATH?

Have you ever wondered how your computer knows where to find the programs you’re trying to run among folder-to-folder? This is where the PATH environment variable steps in like a smart assistant, guiding the system to the right locations.

Subscribe To Our Newsletter

PATH is an environment variable in operating systems such as Unix-like systems, DOS, OS/2, and Microsoft Windows that tells the system which directories to search for executable files. When you type a command like ‘python’ into the command line, the operating system uses the PATH setting to find the ‘python’ executable without needing the full address.

Understanding the Windows System Path

In Windows, the PATH environment variable is critical for the smooth running of software. It includes a list of directories where executable programs reside, separated by semicolons. 

Typically, C:WINDOWSsystem32 stands at the forefront, followed by directories of certain installed software. Not every program requires a spot in the Windows PATH since many are designed for a Graphical User Interface (GUI) rather than command-line initiation.

Imagine each working directory listed in the PATH, including the system directory, as a desktop shortcut that Windows can take to swiftly access the tools or programs you’re instructing it to run. You’re telling Windows, “Hey, here are the places you should look when I command you to execute something.” Not every application you install will add itself to this list—only those often used from the command line.

Here’s a breakdown of the typical components within a Windows system PATH, including command-line and Windows GUI elements crucial in managing system data.

  • System Directories: These are essential paths that Windows uses by default, such as C:WINDOWSsystem32 and C:WINDOWS.
  • Third-Party Software: Programs that must be accessible via the command line might add their paths here during installation.
  • Extra Utilities: Tools and utilities like Git, Node.js, or Python often suggest adding themselves to the PATH during their setup process.

When introducing new tools to your workflow, you’ll sometimes need to add their directories to Windows PATH manually. While this is a straightforward process, it’s important to approach it with caution because an improperly configured PATH can lead to system errors or command conflicts. Appropriate fixes should be applied promptly if issues arise to maintain system stability.

By understanding how the system PATH works, including the PowerShell window, you enable yourself to significantly extend the functionality of your command-line experience, making it a valuable skill for efficiency and productivity when working with Windows.

Navigating to Environment Variables in Windows 11

You’ll first need to access the Environment Variables to manage your computer’s system PATH in Windows 11, which involves a couple of steps. First, right-click on the ‘This PC’ or ‘Computer’ icon on your desktop, and then select ‘Properties’. From there, they’re neatly tucked away in the System Properties, where you can edit your PATH to include the necessary directories.

  • Right-click on the Start menu.
  • Select ‘System.’
  • Click on ‘About’ followed by ‘Advanced system settings.’
  • In the ‘System Properties’ window, click ‘Environment Variables.’

Setting or Editing Environment Variables

Adding a new directory to your Windows PATH can unlock new command-line powers for you. To do this, select ‘PATH’ in the Environment Variables window and click the ‘Edit’ button. You can either append a new directory to the list or edit existing entries, separating them with a semicolon. Remember only to add directories that contain executable files you need to run from the command prompt.

5 Tips for Effective Path Management

Navigating your operating system’s environment variables, including the PATH parameter, can be as crucial as setting the sails correctly before a sea journey—you want to ensure everything’s optimized for smooth sailing.

When it comes to PATH management in Windows, understanding and adjusting this path parameter with a few handy tips can make your voyage through the digital seas much less daunting and far more efficient.

  1. Keep Path Backup: Before altering your PATH, it’s wise to chart your current course. Simply put, copy your existing PATH variable’s value and keep it in a safe harbor—a text file or cloud storage. This foresight can be a lifesaver in choppy waters.
  2. Meaningful Additions Only: Your PATH is not a treasure chest to be filled with every shiny object. Adding only necessary directories reduces the risk of overflowing your PATH and encountering haunted system errors. It’s the quality, not the quantity, that counts.
  3. Cohesive Grouping: Arrange associated paths together. This organizes your collection of paths so that they’re more readable and manageable, like a well-organized chart that guides you to your destination without unnecessary detours.
  4. Leverage Environment Variables: Incorporate other environment variables within your PATH. For example, referring to %USERPROFILE% instead of C:UsersYourName makes your PATH dynamically adjust to different users and system configurations, like a compass that automatically adjusts to true north.
  5. Regular Audits: Every so often, take a voyage through your PATH variables and clear out any that no longer serve a purpose, like removing barnacles from a ship’s hull to improve its speed and handling.

By keeping these navigational aids in mind, including ensuring Drive C is clutter-free, you can ensure that managing your PATH, an essential aspect of desktop optimization is a voyage of discovery, not a journey into frustration.

With a shipshape PATH and an organized Drive C, you’ll find that launching applications and executing tasks from the command line is a breeze, enhancing both your PC’s performance and your own productivity.

Remain attentive and systematic in your approach; you’ll find PATH management indispensable in your Windows toolkit. Including .bat extension files in your PATH can be a powerful addition, allowing the execution of batch scripts with a simple command.

With the right strategy, patience, and the ability to copy and paste critical PATH entries accurately, you’ll find managing your PATH isn’t just about upkeep; it’s about enabling new possibilities and streamlining your workflow.

Windows Path Checklist

5 Best Practices for Customizing Environment Variables

Customizing environment variables can feel like tuning a high-performance engine: each adjustment can improve efficiency and power. To ensure your computing environment runs like a well-oiled machine, here are some best practices to consider when customizing environment variables, especially the sensitive PATH variable.

  1. Validate Path Entries: Ensure it’s correct before adding a new path. Navigate the right directory name to verify its existence and check for typos. A wrong turn here could lead to a dead-end for your commands.
  2. Scope Appropriately: If all users use a software tool on a computer, elevate its path to the system variables; for personal tools, confine their paths to user variables. This is like choosing whether to build a private or public road.
  3. Avoid Unnecessary Changes: Treat system paths with respect. Refrain from deleting entries unless you are certain they serve no purpose. Removing the wrong path can lead to system-wide gridlock.
  4. Use Clear Variable Names: When creating a new environment variable, label it with a name that evokes its purpose. It’s like putting a sign on a road—it helps everyone navigate more easily.
  5. Consult with Experts: If you’re in uncharted waters, don’t hesitate to seek guidance from experienced users or IT professionals. A little expert advice goes a long way in preventing mishaps.

By adopting these best practices and their tactful implementation, your interactions with environment variables will be less about trial and error and more about precision and control. 

Setting up an icon for different variables can enhance your navigating efficiency. Your effort to manage your Windows PATH intelligently can significantly boost your productivity and safeguard against common computing pitfalls.

Treat these best practices as your navigational stars, guiding you toward a more secure, stable, and swift computing experience, including safer ways to browse the internet through the security pane.

How Can Full Scale Help You?

If you want to take your project to the next level with state-of-the-art software development solutions, consider partnering with Full Scale.

With a reputation for excellence in offshore software development, Full Scale offers top-tier expertise to help you reach your project goals efficiently and effectively. Don’t settle for less; choose Full Scale for a team that’s as invested in your success as you are.

Remember, whether you’re just starting or scaling up, Full Scale is the partner you need for all your offshore software development requirements, including server management. Make the smart choice for your business and reach out now.

FAQs in Setting the Windows Path and Your Environment Variables

As you embark on the journey of customizing your Windows PATH and environment variables, questions may arise. For instance, you might wonder how to add a new path – that’s where a dialog box comes into play. Below are answers to some frequently asked questions that could help you avoid common obstacles, including navigating dialog boxes effectively.

1. What happens if I mess up my PATH?

Don’t worry! You can restore your PATH if you’ve made a backup. Otherwise, you may need to reinstall programs or reset the PATH manually.

2. Can I set temporary PATH variables?

Yes, you can set temporary PATH variables for a session by using the set command in the command prompt.

3. Do I need to restart after changing PATH?

Changes to PATH usually take effect immediately in new command prompt windows; a restart is not typically necessary.

4. How do I add multiple directories to PATH?

You can add multiple directories to streamline the directory search by separating them with semicolons in the PATH variable’s value.

5. Is there a limit to the number of entries in PATH?

Windows has a character limit for PATH that includes the filename, and a colon designates this limit. If this limit is exceeded, you may experience problems, so keep your filepaths and filenames as concise as possible.

Matt Watson is a serial tech entrepreneur who has started four companies and had a nine-figure exit. He was the founder and CTO of VinSolutions, the #1 CRM software used in today’s automotive industry. He has over twenty years of experience working as a tech CTO and building cutting-edge SaaS solutions.

As the CEO of Full Scale, he has helped over 100 tech companies build their software services and development teams. Full Scale specializes in helping tech companies grow by augmenting their in-house teams with software development talent from the Philippines.

Matt hosts Startup Hustle, a top podcast about entrepreneurship with over 6 million downloads. He has a wealth of knowledge about startups and business from his personal experience and from interviewing hundreds of other entrepreneurs.

The PATH is an important concept when working on the command line. It’s a list of directories that tell your operating system where to look for programs, so that you can just write script instead of /home/me/bin/script or C:\Users\Me\bin\script. But different operating systems have different ways to add a new directory to it:

For Windows

  1. The first step depends which version of Windows you’re using:

    • If you’re using Windows 8 or 10, press the Windows key, then search for and select «System (Control Panel)».

    • If you’re using Windows 7, right click the «Computer» icon on the desktop and click «Properties».

  2. Click «Advanced system settings».

  3. Click «Environment Variables».

  4. Under «System Variables», find the PATH variable, select it, and click «Edit». If there is no PATH variable, click «New».

  5. Add your directory to the beginning of the variable value followed by ; (a semicolon). For example, if the value was C:\Windows\System32, change it to C:\Users\Me\bin;C:\Windows\System32.

  6. Click «OK».

  7. Restart your terminal.


For Mac OS X

  1. Open the .bash_profile file in your home directory (for example, /Users/your-user-name/.bash_profile) in a text editor.

  2. Add export PATH="your-dir:$PATH" to the last line of the file, where your-dir is the directory you want to add.

  3. Save the .bash_profile file.

  4. Restart your terminal.


For Linux

  1. Open the .bashrc file in your home directory (for example, /home/your-user-name/.bashrc) in a text editor.

  2. Add export PATH="your-dir:$PATH" to the last line of the file, where your-dir is the directory you want to add.

  3. Save the .bashrc file.

  4. Restart your terminal.

You may also like:

  • WhatsApp Automation to Send Message using Python
  • Best 17 OCR Software/Web Apps
  • How to Crack an IT Job Interview?
  • Hide Your Personal Files Inside Images Without Using any Software

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как посмотреть когда было последнее обновление windows 10
  • Как изменить цвет стрелки мыши на windows 10
  • Windows 7 sp2 download iso
  • Nmap for windows portable
  • Ftp как локальный диск windows