Изменить каталог в командной строке windows


Загрузить PDF


Загрузить PDF

В этой статье рассказывается, как перейти в другую папку (каталог) в командной строке Windows. Чтобы работать с командной строкой, необходимо использовать учетную запись администратора.

  1. Изображение с названием Change Directories in Command Prompt Step 1

    1

    Откройте меню «Пуск». Для этого щелкните по логотипу Windows в нижнем левом углу экрана или нажмите клавишу Win на клавиатуре.

    • В Windows 8 переместите указатель мыши в верхний правый угол экрана и щелкните по отобразившемуся значку в виде лупы.
  2. Изображение с названием Change Directories in Command Prompt Step 2

    2

    В строке поиска введите командная строка. Значок утилиты командной строки отобразится над строкой поиска.

  3. Изображение с названием Change Directories in Command Prompt Step 3

    3

    Щелкните правой кнопкой мыши по значку командной строки. Он имеет вид черного квадрата. Откроется контекстное меню.

  4. Изображение с названием Change Directories in Command Prompt Step 4

    4

    Нажмте Запуск от имени администратора. Эта опции находится в верхней части раскрывшегося меню. Откроется командная строка с правами администратора.

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

    Реклама

  1. Изображение с названием Change Directories in Command Prompt Step 5

    1

    Введите cd . После «cd» обязательно добавьте пробел. Эта команда, которая представляет собой сокращение от «change directory» (изменить каталог), является основной командой для перехода в другой каталог.

    • Не нажимайте клавишу Enter.
  2. Изображение с названием Change Directories in Command Prompt Step 6

    2

    Определите путь к нужному каталогу. Путь к каталогу похож на перечень папок. Например, если нужным каталогом является папка «System32», которая находится в папке «WINDOWS» на системном диске, путь будет таким: «C:\WINDOWS\System32\».

    • Чтобы выяснить путь к папке, откройте окно «Мой компьютер», дважды щелкните по значку жесткого диска, перейдите в нужную папку, а затем скопируйте информацию из адресной строки Проводника (сверху).
  3. Изображение с названием Change Directories in Command Prompt Step 7

    3

    Введите путь к каталогу. Сделайте это после команды «cd». Убедитесь, что между «cd» и путем к каталогу есть пробел.

    • Например, команда может выглядеть так: cd Windows\System32 или cd D:.
    • По умолчанию местоположением всех папок считается жесткий диск (например, «C:»), поэтому букву жесткого диска вводить не нужно.
  4. Изображение с названием Change Directories in Command Prompt Step 8

    4

    Нажмите Enter. Так вы перейдете в нужный каталог.

    Реклама

Советы

  • Изменить каталог необходимо, чтобы отредактировать или удалить файл.
  • Некоторыми общими командами для работы с каталогами являются следующие:
    • D: или F: – изменить каталог на дисковод или подключенный флеш-накопитель.
    • .. – переместиться из текущего каталога на одну папку вверх (например, из «C:\Windows\System32» в «C:\Windows»).
    • /d – одновременно изменить диск и каталог. Например, если в командной строке вы находитесь в корневом каталоге диска «D:», введите «cd /d C:\Windows», чтобы перейти в папку «Windows» на диске «C:».
    • \ – перейти в корневой каталог (например, системного диска).

Реклама

Предупреждения

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

Реклама

Об этой статье

Эту страницу просматривали 711 939 раз.

Была ли эта статья полезной?

Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на Github или отредактировать документ в vim. Всё это происходит так часто, что все основные действия с файлами становится быстрее и привычнее выполнять в консоли. Рассказываем и показываем основные команды, которые помогут ускорить работу в терминале под OS Windows.

Для начала нужно установить терминал или запустить командную строку, встроенную в Windows — для этого нажмите Win+R и введите cmd. Терминал часто встречается и прямо в редакторах кода, например, в Visual Studio Code.

Чтобы ввести команду в консоль, нужно напечатать её и нажать клавишу Enter.

Содержимое текущей папки — dir

Выводит список файлов и папок в текущей папке.

C:\content-server>dir
 Том в устройстве C имеет метку SYSTEM
 Серийный номер тома: 2C89-ED9D

 Содержимое папки C:\content-server

06.10.2020  00:41    <DIR>          .
06.10.2020  00:37    <DIR>          .circleci
16.07.2020  16:04               268 .editorconfig
16.07.2020  16:04                10 .eslintignore
16.07.2020  16:04               482 .eslintrc
06.10.2020  00:37    <DIR>          .github
16.07.2020  16:04                77 .gitignore
06.10.2020  00:41    <DIR>          assets
06.10.2020  00:41    <DIR>          gulp
16.07.2020  16:10               379 gulpfile.js
16.07.2020  16:10           296 320 package-lock.json
16.07.2020  16:10               751 package.json
16.07.2020  16:04               509 README.md

Открыть файл

Чтобы открыть файл в текущей папке, введите его полное имя с расширением. Например, blog.txt или setup.exe.

Перейти в другую папку — cd

Команда cd без аргументов выводит название текущей папки.

Перейти в папку внутри текущего каталога:

C:\content-server>cd assets
C:\content-server\assets>

Перейти на одну папку вверх:

C:\content-server\assets>cd ..
C:\content-server>

Перейти в папку на другом диске:

c:\content-server>cd /d d:/
d:\>

Чтобы просто изменить диск, введите c: или d:.

Создать папку — mkdir или md

Создаём пустую папку code внутри папки html:

d:\html>mkdir coded:\html>dir

 Содержимое папки d:\html

03.11.2020  19:23    <DIR>           .
03.11.2020  19:23    <DIR>           ..
03.11.2020  19:25    <DIR>           code
               0 файлов              0 байт
               3 папок  253 389 438 976 байт свободно

Создаём несколько пустых вложенных папок — для этого записываем их через косую черту:

d:\html>mkdir css\js
d:\html>dir
 Том в устройстве D имеет метку DATA
 Серийный номер тома: 0000-0000

 Содержимое папки d:\html

03.11.2020  19:23    <DIR>           .
03.11.2020  19:23    <DIR>           ..
03.11.2020  19:25    <DIR>           code
03.11.2020  19:29    <DIR>           css

Создаётся папка css, внутри которой находится папка js. Чтобы проверить это, используем команду tree. Она показывает дерево папок.

Удалить папку — rmdir или rd

Чтобы удалить конкретную папку в текущей, введите команду rmdir:

d:\html\css>rmdir js

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

d:\html\css>d:\html>rmdir css
Папка не пуста.

Чтобы удалить дерево папок, используйте ключ /s. Тогда командная строка запросит подтверждение перед тем, как удалить всё.

d:\html>rmdir css /s
css, вы уверены [Y(да)/N(нет)]? y

Показать дерево папок — tree

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

d:\html>tree
Структура папок тома DATA
Серийный номер тома: 0000-0000
D:.
├───code
└───css
    └───js

Если вы хотите посмотреть содержимое всего диска, введите tree в корне нужного диска. Получится красивая анимация, а если файлов много, то ещё и немного медитативная.

Удаление файла — del или erase

Команда для удаления одного или нескольких файлов.

d:\html>del blog.txt

Переименование файла — ren или rename

Последовательно вводим ren, старое и новое имя файла.

d:\html>dir
 Содержимое папки d:\html

03.11.2020  19:23    <DIR>            .
03.11.2020  19:23    <DIR>            ..
03.11.2020  19:59                 0 blag.txt

d:\html>ren blag.txt blog.txt

d:\html>dir
 Содержимое папки d:\html

03.11.2020  19:23    <DIR>            .
03.11.2020  19:23    <DIR>            ..
03.11.2020  19:59                 0 blog.txt

Команды одной строкой

Очистить консоль — cls.

Информация о системе — systeminfo.

d:\html>systeminfo

Имя узла:                         DESKTOP-6MHURG5
Название ОС:                      Майкрософт Windows 10 Pro
Версия ОС:                        10.0.20246 Н/Д построение 20246
Изготовитель ОС:                  Microsoft Corporation
Параметры ОС:                     Изолированная рабочая станция
Сборка ОС:                        Multiprocessor Free

Информация о сетевых настройках — ipconfig.

d:\html>ipconfig
Настройка протокола IP для Windows
Адаптер Ethernet Ethernet 2:

   Состояние среды. . . . . . . . : Среда передачи недоступна.
   DNS-суффикс подключения . . . . . :

Список запущенных процессов — tasklist.

c:\>tasklist

Имя образа                     PID Имя сессии          № сеанса       Память
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         8 КБ
System                           4 Services                   0     2 688 КБ
Secure System                   72 Services                   0    23 332 КБ
…

Справка по командам — help

Команда help без аргументов выводит список всех возможных команд. help вместе с именем команды выведет справку по этой команде.

d:\html>help tree
Графическое представление структуры папок или пути.

TREE [диск:][путь] [/F] [/A]

   /F   Вывод имён файлов в каждой папке.
   /A   Использовать символы ASCII вместо символов национальных алфавитов.

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

👉🏻 Больше статей о фронтенде и работе в айти в телеграм-канале.

Подписаться

Материалы по теме

  • 10 горячих клавиш VS Code, которые ускорят вашу работу
  • Полезные команды для работы с Git
  • Полезные команды для работы с Node. js

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

ТелеграмПодкастБесплатные учебники

Как перейти в папку или на другой диск в командной строке

Работая в командной строке (CMD) все действия приходится выполнять при помощи текстовых команд и переход в другую папку не исключение. Для этого

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

Если вы работаете в командной строке (CMD), то для перехода в другую папку нужно ввести команду CD и название папки. Например, если вы находитесь в корне диска C и хотите перейти в папку Users, то вам нужно вводить команду:

cd Users

переход в другую папку

Для того чтобы вернуться назад (перейти на уровень выше по дереву папок) нужно вводить команду:

cd ..

переход в папку на уровень выше

Для того чтобы быстро перейти в корневый каталог текущего диска нужно выполнить:

cd \

Команду CD можно вводить как СHDIR, логика ее работы от этого не меняется.

Как перейти на другой диск

Если вам нужно перейти на другой диск, например, с диска C на диск D, то команду cd нужно выполнять с параметром /D. Например, если вам нужно перейти с диска C на диск D в папку GAMES, то вам нужно ввести команду:

cd /D d:\games

переход в папку на другом диске

Также вы можете просто ввести букву диска с двоеточием и таким образом перейти на другой диск:

D:

C:

переход на другой диск

Например, если вы находитесь на диске C и вам нужно перейти на диск D, то вы можете просто ввести команду «D:».

Как открыть командную строку сразу в нужной папке

Если вам нужно открыть командную строку в определенной  папке, то это можно сделать прямо из Проводника Windows. Для этого нужно открыть данную папку в Проводнике и установить курсор в адресную строку, там где указывается путь к папке.

После этого нужно удалить путь к папке, ввести команду «cmd» и нажать на клавишу ввода.

В результате откроется командная строка. При этом в качестве текущей папки уже будет выбранна та папка, из которой вы запускали «cmd».

Таким образом из папки можно запускать не только командную строку, но и другие консоли. Например, PowerShell или bash, если у вас установлен WSL. Данный способ работает в Windows 10 и Windows 11.

Посмотрите также:

  • Выключение компьютера через командную строку
  • Как перезагрузить компьютер через командную строку
  • Как вызвать командную строку в Windows 7
  • Как поменять дату в Windows 7
  • Как выключить компьютер через определенное время

Автор
Александр Степушин

Создатель сайта comp-security.net, автор более 2000 статей о ремонте компьютеров, работе с программами, настройке операционных систем.

Остались вопросы?

Задайте вопрос в комментариях под статьей или на странице
«Задать вопрос»
и вы обязательно получите ответ.

I’m using cmd.exe (C:\WINDOWS\System32\cmd.exe) and I have to change my current directory to «D:\temp» i.e. temp folder in the D drive.

When I try to cd nothing happens.

C:\> cd D:\temp

C:\>

I don’t know what else to do here. Even pressing tab key does not give any hints. I have never got the reason to use cmd.exe until now when I have to. I mostly use Linux for development.

If this helps: I’m on a remote login to another computer and D:\temp in on the remote machine, but so is C:\ where I have opened the terminal (cmd.exe).

Mofi's user avatar

Mofi

46.3k17 gold badges81 silver badges145 bronze badges

asked Jul 19, 2013 at 19:25

A. K.'s user avatar

5

The «cd» command changes the directory, but not what drive you are working with. So when you go «cd d:\temp», you are changing the D drive’s directory to temp, but staying in the C drive.

Execute these two commands:

D:
cd temp

That will get you the results you want.

answered Jul 19, 2013 at 19:27

Mark Nenadov's user avatar

Mark NenadovMark Nenadov

6,4415 gold badges24 silver badges33 bronze badges

3

Another alternative is pushd, which will automatically switch drives as needed. It also allows you to return to the previous directory via popd:

C:\Temp>pushd D:\some\folder
D:\some\folder>popd
C:\Temp>_

answered Jul 19, 2013 at 20:18

Ansgar Wiechers's user avatar

Ansgar WiechersAnsgar Wiechers

194k26 gold badges257 silver badges331 bronze badges

2

cd has a parameter /d, which will change drive and path with one command:

cd /d d:\temp

( see cd /?)

answered Jul 19, 2013 at 20:12

Stephan's user avatar

StephanStephan

54.2k10 gold badges58 silver badges93 bronze badges

1

You can try this it works for me

C:\Users\user>cd..
C:\Users>cd ..
C:\>D:
D:\>cd \foldername

answered Dec 18, 2021 at 19:09

Jannatul Fardous's user avatar

Use Command

G:\ D:         <!--Move to D Drive-->

D:\ cd temp      <!--Move to temp Folder-->

answered Sep 27, 2022 at 6:18

Munna Kumar's user avatar

Munna KumarMunna Kumar

3874 silver badges7 bronze badges

Just type your desired drive initial in the command line and press enter

Like if you want to go L:\\ drive,
Just type L: or l:

answered Nov 13, 2020 at 7:17

danialcodes's user avatar

cd /driveName driveName:\pathNamw

answered Jan 4, 2021 at 6:20

pushpendra's user avatar

1

You can use these three commands:
1.cd.. 2.d: 3.cd temp

answered Sep 18, 2021 at 11:03

Divyanshu's user avatar


Download Article

A comprehensive Guide to Changing Directories in the Windows Command Prompt


Download Article

  • Opening Command Prompt
  • |

  • Changing the Directory
  • |

  • Other Directory Commands
  • |

  • Troubleshooting
  • |

  • Q&A
  • |

  • Tips
  • |

  • Warnings

Do you want to know how to change directories in the Windows Command Prompt (CMD)? The Windows Command Prompt allows you to use a variety of advanced commands that give you more control over your computer. However, when learning to use the Command Prompt, you will need to learn some basic commands, including how to navigate by changing directories. A directory is just another name for a folder. This wikiHow teaches you how to change directories in the Windows Command Prompt. To make changes in Command Prompt, you must be using an administrator account.

Things You Should Know

  • Open the Command Prompt (CMD) and type «cd» with a space, followed by the name of the directory, or drag and drop the directory into CMD from File Explorer. Press «Enter.»
  • Type «cd..» and press «Enter» to go back one directory. Type «cd\» and press «Enter» to go to the root of the drive. Type a drive letter (i.e. «D:») and press «Enter» to change drives.
  • Type «dir» and press «Enter» to view all directories in your current directory.
  1. Image titled Change Directories in Command Prompt Step 1

    1

    Open the Windows Start menu {windows|start}}. To do so, click the icon with the Windows logo in the taskbar at the bottom of the screen. Alternatively, you can press the Windows key.

    • For Windows 8, place your mouse cursor in the top-right corner of the screen, then click the magnifying glass icon when it appears.
  2. Image titled Change Directories in Command Prompt Step 2

    2

    Type in cmd. This will bring up the Command Prompt icon at the top of the Start window.

    Advertisement

  3. Image titled Change Directories in Command Prompt Step 3

    3

    Right-click Command Prompt

    Windows cmd

    . It resembles a black box with a white cursor. This displays a drop-down menu.

  4. Image titled Change Directories in Command Prompt Step 4

    4

    Click Run as administrator. It’s near the top of the drop-down menu. Doing so will open the Command Prompt with administrator privileges.

    • Confirm this choice by clicking Yes when prompted.
    • You won’t be able to run Command Prompt in administrator mode if you are not signed into an Administrative account, or if you’re on a restricted, public, or networked computer (e.g., a library or school computer).
  5. Advertisement

  1. Image titled Change Directories in Command Prompt Step 5

    1

    Type in cd followed by a space. This command, which stands for «change directory», is the root of any directory change.

    • Don’t press the «Enter» key just yet.
    • Alternatively, you can type chdir. This command does the exact same thing as «cd.»[1]
  2. Image titled Change Directories in Command Prompt Step 6

    2

    Determine your directory’s path. A directory path is like a map to a specific folder. For example, if the directory to which you want to change is the «System32» folder that’s, in the «Windows» folder on the hard drive, the path would be «C:\Windows\System32\.»

    • You can find a folder by navigating to it in File Explorer. Click the address bar at the top to display the path to the folder you are currently in.
    • You can display a list of all directories in your current directory in the Command Prompt by typing dir and pressing «Enter
  3. Image titled Change Directories in Command Prompt Step 7

    3

    Type in your directory’s path. Your command or address goes after the «cd» command; make sure there is a space between «cd» and your command.

    • For example, your whole command might look like cd Windows\System32.
    • Alternatively, you can drag and drop a folder from File Explorer into the Command Prompt.
    • If the directory is in the current drive you are in, you do not need to type the drive letter at the beginning of the path.
  4. Image titled Change Directories in Command Prompt Step 8

    4

    Press Enter. Doing so will change the Command Prompt directory to your selected one. The current directory you are in is listed next to the text cursor (i.e. «C:\Windows\System32>».)

  5. Advertisement

  1. 1

    Type cd.. and press Enter to go back a directory. If you want to go back one directory (i.e. change from «C:\Windows\System32» to «C:\Windows»), simply type «cd..» with two periods and press «Enter

  2. 2

    Type cd\ and press Enter to return to the root of your drive. If you want to go back to the root of your drive (i.e. go from «C:\Windows\System32» to «C:\»), simply type «cd\» with a back slash and press «Enter

  3. 3

    Type a drive letter and press Enter to change drives. If you try using the «cd» command to change directories to a directory that is on another drive, you will notice it does not work. You need to change drives before changing to a directory on that drive. To do so, type the drive letter (i.e. «D:») with a colon and press «Enter» to change drives.

    • Alternatively, you can type cd /d followed by the complete path (including the drive letter) of a directory on another drive to change directly to that drive (i.e. «cd /d D:\Documents».)
  4. 4

    Type dir and press Enter to list directories in your current directory. If you are not sure what directories are in your current directory, you can display a list of all the directories by typing «dir» and pressing «Enter

  5. Advertisement

  1. 1

    Check that you are spelling the directory name correctly. If you receive an error message that says «The system cannot find the path specified,» check to make sure you are spelling the name of the directory correctly. You can see a list of all directories in your current directory by typing dir and pressing «Enter

  2. 2

    Check to make sure the directory exists. If you are spelling is correct and you are still getting the same error, open File Explorer and check to make sure the directory you are navigating to actually exists and that it’s located where you think it’s located.

    • If the directory does not exist, you can create a new directory by typing mkdir followed by a space, followed by the name of the directory you want to create. Then press «Enter
  3. 3

    Make sure the directory is located on the drive that you are currently in. The «cd» command will not allow you to change to a directory on another drive. If you are currently in the «C:» drive, but the directory you want to change to is on the «D:» drive, you will need to change drive letters before changing to a new directly. You can do so by typing the drive letter and pressing «Enter

  4. 4

    Make sure you are running the Command Prompt as an administrator. If you are not running the Command Prompt as an administrator, you will be limited in what you can do with the Command Prompt. Make sure you are logged into Windows as an Administrator, then right-click the CMD icon in the Start menu and click Run as Administrator.

  5. Advertisement

Add New Question

  • Question

    How do I go to C:\ from C:\users\username?

    Community Answer

    You can either type «cd ..» to take you up a directory level (to C:\users) and once again to take you to the root level, or you can always type «cd \» from any directory to take you to the root level.

  • Question

    How do I change the name of a drive, like from Drive H: to drive A:?

    Community Answer

    In start, type Computer Management. Open Computer Management and click the arrow next to Storage, then Disk Management. Right-click the drive you want to rename and click Change Drive Letter.

  • Question

    What is the difference between cd\ and cd?

    Community Answer

    In order to use cd you have to put a file path after it; cd\ just goes straight to C:\.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

  • Changing the directory is useful when attempting to modify or delete a file in a specific location.

Thanks for submitting a tip for review!

Advertisement

  • Attempting to run a command that is contingent on a specific file or folder while in a different directory will result in errors.

Advertisement

About This Article

Thanks to all authors for creating a page that has been read 2,472,836 times.

Is this article up to date?

  • Изменился вид рабочего стола windows 10
  • Изменить окно поиска в windows
  • Изменить картинку загрузки windows 10
  • Изменить общедоступную сеть на частную windows server 2012
  • Изменить имя компьютера windows 10 через командную строку