Как указать путь к файлу в командной строке windows 10

Users can run an executable from windows command prompt either by giving the absolute path of the file or just by the executable file name. In the latter case, Windows searches for the executable in a list of folders which is configured in environment variables. These environment variables are as below.

1. System path
2. User path

The values of these variables can be checked in system properties( Run sysdm.cpl from Run or computer properties). Initially user specific path environment variable will be empty. Users can add paths of the directories having executables to this variable. Administrators can modify the system path environment variable also.

How to set path from command line?

In Vista, Windows 7 and Windows 8 we can set path from command line  using ‘setx’ command.

setx path "%path%;c:\directoryPath"

For example, to add c:\dir1\dir2 to the path variable, we can run the below command.

setx path "%path%;c:\dir1\dir2"

Alternative way is to use Windows resource kit tools ‘pathman.exe‘. Using this command we can even remove a directory from path variable. See download windows resource kit tools. This works for Windows 7 also.

Add directory to system path environment variable:

Open administrator command prompt
Run  the below command

pathman /as directoryPath

Remove path from system path environment variable:
Run the below command from elevated command prompt

pathman /rs directoryPath

Setting user path environment variable

For user environment varlables, admin privileges are not required. We can run the below command to add a directory to user path environment variable.

pathman /au directoryPath

To remove a directory from user path, you can run the below command.

pathman /ru directoryPath

Default option is not allowed more than ‘2’ time(s)

You get this error if you have not enclosed ‘path’ in double quotes. See the below example for setting the path of firefox.

C:\Users\>setx path %path%;"c:\Program Files (x86)\Mozilla Firefox\"
ERROR: Invalid syntax. Default option is not allowed more than '2' time(s).
Type "SETX /?" for usage.

Now if you move %path% to be in the double quotes

C:\Users\>setx path "%path%;c:\Program Files (x86)\Mozilla Firefox\"
SUCCESS: Specified value was saved.
C:\Users\>

Для быстрого доступа к командам в командной строке без необходимости ввода полного пути к исполняемому файлу можно добавить путь к папке с этими исполняемыми файлами в переменную PATH в Windows, особенно это может быть полезным при работе с adb, pip и python, git, java и другими средствами разработки с отладки.

В этой пошаговой инструкции о том, как добавить нужный путь в системную переменную PATH в Windows 11, Windows 10 или другой версии системы: во всех актуальных версиях ОС действия будут одинаковыми, а сделать это можно как в графическом интерфейсе, так и в командной строке или PowerShell. Отдельная инструкция про переменные среды в целом: Переменные среды Windows 11 и Windows 10.

Добавление пути в PATH в Свойствах системы

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

Шаги будут следующими:

  1. Нажмите клавиши Win+R на клавиатуре (в Windows 11 и Windows 10 можно нажать правой кнопкой мыши по кнопке Пуск и выбрать пункт «Выполнить»), введите sysdm.cpl в окно «Выполнить» и нажмите Enter.
  2. Перейдите на вкладку «Дополнительно» и нажмите кнопку «Переменные среды».
    Открыть настройки переменных среды Windows

  3. Вы увидите список переменных среды пользователя (вверху) и системных переменных (внизу). PATH присутствует в обоих расположениях.
    Переменная среды PATH пользователя и системная

  4. Если вы хотите добавить свой путь в PATH только для текущего пользователя, выберите «Path» в верхней части и нажмите «Изменить» (или дважды нажмите по переменной PATH в списке). Если для всех пользователей — то же самое в нижней части.
  5. Для добавления нового пути нажмите «Создать», а затем впишите новый путь, который требуется добавить в переменную PATH в новой строке. Вместо нажатия «Создать» можно дважды кликнуть по новой строке для ввода нового пути.
    Добавление папки в переменную PATH

  6. После ввода всех необходимых путей нажмите «Ок» — ваша папка или папки добавлены в переменную PATH.

Внимание: после добавления пути в переменную PATH потребуется перезапустить командную строку (если она была запущена в момент изменения), чтобы использовать команды без указания полного пути.

Как добавить путь в переменную PATH в командной строке и PowerShell

Вы можете добавить переменную PATH для текущей сессии в консоли: то есть она будет работать до следующего запуска командной строки. Для этого используйте команду:

set PATH=%PATH%;C:\ваш\путь

Есть возможность добавить путь в PATH с помощью командной строки и на постоянной основе (внимание: есть отзывы, что может повредить записи в переменной PATH, а сами изменения производятся для системной переменной PATH), команда будет следующей:

setx /M path "%path%;C:\ваш\путь"
Добавление в PATH в командной строке

Набор команд для добавления пути в переменную PATH пользователя с помощью PowerShell:

$PATH = [Environment]::GetEnvironmentVariable("PATH")
$my_path = "C:\ваш\путь"
[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "User")

Если требуется добавить путь в системную переменную PATH для всех пользователей, последнюю команду изменяем на:

[Environment]::SetEnvironmentVariable("PATH", "$PATH;$my_path", "Machine")

PATH is an environment variable that specifies a set of directories, separated with semicolons (;), where executable programs are located.

In this note i am showing how to print the contents of Windows PATH environment variable from the Windows command prompt.

I am also showing how to add a directory to Windows PATH permanently or for the current session only.

Cool Tip: List environment variables in Windows! Read More →

Print the contents of the Windows PATH variable from cmd:

C:\> path

– or –

C:\> echo %PATH%

The above commands return all directories in Windows PATH environment variable on a single line separated with semicolons (;) that is not very readable.

To print each entry of Windows PATH variable on a new line, execute:

C:\> echo %PATH:;=&echo.%
- sample output -
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
C:\WINDOWS\System32\WindowsPowerShell\v1.0\
C:\WINDOWS\System32\OpenSSH\
C:\Program Files\Intel\WiFi\bin\
C:\Program Files\Common Files\Intel\WirelessCommon\
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL
C:\Program Files\Intel\Intel(R) Management Engine Components\DAL
C:\Program Files\Microsoft VS Code\bin
C:\Users\Admin\AppData\Local\Microsoft\WindowsApps

Cool Tip: Set environment variables in Windows! Read More →

Add To Windows PATH

Warning! This solution may be destructive as Windows truncates PATH to 1024 characters. Make a backup of PATH before any modifications.

Save the contents of the Windows PATH environment variable to C:\path-backup.txt file:

C:\> echo %PATH% > C:\path-backup.txt

Set Windows PATH For The Current Session

Set Windows PATH variable for the current session:

C:\> set PATH="%PATH%;C:\path\to\directory\"

Set Windows PATH Permanently

Run as Administrator: The setx command is only available starting from Windows 7 and requires elevated command prompt.

Permanently add a directory to the user PATH variable:

C:\> setx path "%PATH%;C:\path\to\directory\"

Permanently add a directory to the system PATH variable (for all users):

C:\> setx /M path "%PATH%;C:\path\to\directory\"

Info: To see the changes after running setx – open a new command prompt.

Was it useful? Share this post with the world!

You may often need to access a file or a folder that is placed on a different device using the Command Line Interface (CLI) on your Windows 10 device. It may be because you need to execute the package or for any other reason. However, the simple Change Directory (cd) command in the Command Prompt is not sufficient to navigate to a path over the network.

This article discusses various methods and techniques you can use to access or even map network paths onto your device using the command lines.

Table of Contents

Traditional methods to map and access network paths in Windows 10

Normally, users would access a network path using either Run or directly from the File Explorer. We shall also be discussing this method so that you understand the differences when we try and access a network path through the CLI.

  1. To map a network drive using File Explorer, click on This PC in the left navigation bar, and then click Map a network drive from the top menu within the Explorer.
    exp map

  2. A Map network drive wizard will now popup. Select a vacant alphabet to assign to the new drive, enter its path in the field below, select your preference by checking the boxes below, and then click Finish.
    exp wizard

    Note that the IP address on the network path can be changed to the name of the device. Moreover, the path is not case-sensitive, therefore the capital and small should not matter.

  3. You will now be prompted to enter the credentials of the destination user account to access the path. Enter the correct credentials and click OK.
    credentials

You can now check that the path should be added as an attached drive on your PC in the File Explorer.

You can also access the network path directly through the Explorer or Run by typing in the path and providing the correct credentials.

run and exp

This is a convenient way to map and access network drives using the Graphical User Interface (GUI). However, what if you need to access certain files using the CLI and then execute them directly from there? We have a solution for you down below.

How to access network path using command line in Windows 10

You might know how to move around within your own computer using the Command Prompt or Windows PowerShell. However, moving to a path over the network is a different story.

Access network path from Command Prompt using Pushd command

Changing directories within the Command Prompt can be done by using the cd command. However, this does not work when accessing a remote path, and you will get an error stating “CMD does not support UNC paths as current directories.”

UNC path

The Universal Naming Convention (UNC) path is any path consisting of double forward or backslashes followed by a computer name/ IP address. This is not supported by Command Prompt and does not understand the command.

You need to use the pushd command to access a network path from the Command Prompt. Use the command below to do so:

pushd NetworkPath

Replace NetworkPath with the path to the location you wish to access over the network, such as in the example below:

pushd \\itechticsserver\sharedfolder
cmd pushd

Tip: If the location folder has space in its name, enclose the entire NetworkPath in inverted-commas (“”).

As you may notice in the image above, entering the command changed the working directory to z. This letter has been automatically assigned to the path, which is now also mapped and can be seen as a drive using the File Explorer.

Another way to access a network path from Command Prompt is to manually map it using the File Explorer traditionally, and then use the cd command to change the directory using the new assigned drive letter, as in the image below:

Map network path from Command Prompt using Net Use command

Another quick way to access a network path from Command Prompt is to use the Net Use command to initially map the location. This method allows you to mount the network drive as well as set a custom letter for it.

Use the command below to map location over the network:

net use Letter: NetworkPath /PERSISTENT:YES

Replace Letter with a vacant drive letter for the path and replace NetworkPath with the path to the location you want to access. Here is an example of using this command:

persistent

Now that the location has been mapped, simply use the cd command to access it.

Access network path from PowerShell using cd command

Unlike the Command Prompt, Windows PowerShell understands the UNC path, hence is able to use the cd command to change its directory. This method is easier as it is like accessing a local location rather than something over the internet.

Use the command below in PowerShell to access a network path:

cd NetworkPath

Replace NetworkPath with the location you wish to access, as in the example below:

ps cd

Mind you, this approach does not map the location, but only lets you access it via Windows PowerShell.

Closing words

There are multiple ways to access a network path using just the CLI. However, it is up to you to decide which method to use.

If you are required to run certain scripts after accessing the network path, we recommend that you use PowerShell to do so. However, if you have to perform basic tasks such as executing a package and obtain results within the CLI, the Command Prompt Should be enough.

If you simply want to browse the location, the traditional File Explorer should be sufficient for that.

Навигация

Основы командной строки

  • Как проверить, в какой директории мы находимся
  • Как посмотреть список файлов
  • Как переместиться в другую директорию

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

В командной строке все устроено иначе: после загрузки системы мы попадаем в режим ожидания ввода команды. Этот режим привязан к файловой системе. Можно сказать, что мы всегда находимся внутри какой-то директории, которую называют рабочей директорией (working directory).

В этом уроке мы поговорим о навигации по директориям через командную оболочку.

Как проверить, в какой директории мы находимся

Начнем с самого основного. Проверить, в какой директории мы сейчас находимся, можно командой pwd:

pwd

/Users/guest

Кстати, название команды pwd — это сокращение, которое расшифровывается как print working directory. Похожим образом устроены имена многих команд, что позволяет легче и быстрее их запомнить.

По умолчанию новая сессия командной оболочки открывается внутри домашней директории пользователя. У каждого пользователя своя домашняя директория, поэтому в вашем случае путь будет отличаться.

В приведенном примере есть две неожиданности для тех, кто привык пользоваться Windows:

  1. В начале указан не диск, а единый корневой каталог /. Это вершина файловой системы, внутри которой лежат все остальные файлы и директории
  2. Вместо обратных слэшей \ используются прямые слэши /

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

Как посмотреть список файлов

Изучим команду ls (сокращение от list). Она выводит список файлов и директорий в текущей рабочей директории:

ls

Desktop  Documents Downloads Library  Movies  Music  Pictures Public

Как переместиться в другую директорию

Еще одна полезная команда — cd (сокращение от change directory). С помощью нее мы перемещаемся по файловой структуре. Для этого ей нужно передать аргумент — директорию, в которую необходимо переместиться:

# Входим в директорию
cd Music
# Смотрим ее содержимое
ls

iTunes
# Смотрим текущую рабочую директорию
pwd

/Users/guest/Music
# Если имя директории содержит пробел, то его нужно экранировать с помощью `\`
cd Best\ music

Остановимся на этом моменте подробнее. Возможно, вы знаете, что есть два способа обозначить путь до файла:

  • Абсолютный путь начинается от корня
  • Относительный путь начинающийся от текущей рабочей директории

Выше мы указали относительный путь. Отличить их друг от друга очень легко:

  • Абсолютный — первым символом в пути идет /
  • Относительный — во всех остальных случаях

Когда мы используем относительный путь, команда cd считывает его и внутри себя пытается вычислить абсолютный путь. Она берет текущую рабочую директорию /Users/guest/ и присоединяет к ней Music. В итоге получается /Users/guest/Music.

Команда cd понимает и абсолютные, и относительные пути. Поэтому передавать ей можно что угодно:

# Неважно, в каком месте
cd /Users/guest/Music # Абсолютный путь

Еще раз проговорим, что абсолютный путь однозначно определяет адрес файла или директории в файловой системе, а относительный — нет.

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

Теперь рассмотрим другую задачу. Предположим, что мы находимся в директории /Users/guest/Music. Как выйти из нее и попасть снова в /Users/guest? Мы уже знаем один способ — указать абсолютный путь и сделать cd:

cd /Users/guest

Но есть путь проще. Можно указать специальное значение .. и перейти на директорию уровнем выше:

# В директории /Users/guest/Music
cd ..
pwd

/Users/guest

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

# В директории /Users/guest/Music
# Выходим на два уровня вверх
cd ../..
pwd

/Users

Иногда в пути используется одинарная точка, которая означает текущую директорию. Например, вместо cd Music можно писать cd ./Music — разницы между этими выражениями нет.

Есть и третий вариант возврата в /Users/guest из директории /Users/guest/Music. Можно выполнить команду cd без аргументов, тогда мы перейдем в домашнюю директорию текущего пользователя:

# Из любого места
cd
pwd

/Users/guest

Ну и, наконец, четвертый вариант. Домашняя директория пользователя имеет специальное обозначение — ~ (тильда). В момент выполнения команды тильда заменяется на абсолютный путь. Поэтому из любого места можно напрямую перейти в любую поддиректорию домашней директории:

# Из любого места
cd ~/Music
pwd

/Users/guest/Music

Допустим, вы находитесь в домашней директории и хотите посмотреть файлы в поддиректории Music. Один способ вы уже знаете — для этого нужно перейти в директорию Music и выполнить программу ls.

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

ls Music

iTunes

Как и в случае с командой cd, к аргументу ls применимы понятия абсолютных и относительных путей. Впрочем, это правило распространяется на большинство случаев, где передаются пути.

Команда cd - возвращает в предыдущую директорию. Другими словами, последовательный вызов этой команды переключает между двумя последними посещенными директориями.

Команды cd, ls и pwd вместе составляют основу навигации по файловой структуре. Зная их, вы никогда не потеряетесь и не запутаетесь.

Со временем набирать пути становится все более лениво. Тогда можно дважды нажать Tab и воспользоваться автокомплитом — функцией, которая автоматически завершает имена.


Самостоятельная работа

Изучите содержимое директорий своей файловой системы. При перемещении между разделами с помощью команды cd используйте клавишу Tab для автозаполнения.

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно


  • 130 курсов, 2000+ часов теории

  • 1000 практических заданий в браузере

  • 360 000 студентов

Наши выпускники работают в компаниях:

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ru windows vista with sp2 x86 dvd x15 36309 iso
  • Год прекращения поддержки windows 7
  • Windows 10 pro original iso torrent
  • После загрузки обновлений windows 7 не запускается
  • Недостаточно свободных ресурсов для работы данного устройства код 12 windows 10