Command for windows cmd

«CMD for» refers to using command-line interface commands in Windows to execute various tasks efficiently, such as checking system information or managing files and directories.

Here’s a code snippet to demonstrate how to check your IP configuration using CMD:

ipconfig

Getting Started with CMD

Accessing Command Prompt

To begin your journey with CMD for Windows, the first step is accessing the Command Prompt. Here’s how you can do it:

  • Open the Command Prompt: You can easily access CMD by typing `cmd` in the Windows search bar. Alternatively, press `Windows + R` to open the Run dialog, type `cmd`, and hit Enter. Another way is to open Task Manager (`Ctrl + Shift + Esc`), go to File > Run new task, and enter `cmd`.

Understanding CMD Interface

Once you have opened Command Prompt, familiarizing yourself with its components is crucial.

Basic Components of CMD: The main area is where you will be entering commands. The prompt symbol (usually `C:\>` or similar) indicates that the system is ready to accept commands.

Navigating the CMD Interface: CMD responds to simple keyboard navigation. Use the arrow keys to scroll through previous commands, and familiar shortcuts like `Ctrl + C` to copy and `Ctrl + V` to paste commands enhance your efficiency.

Mastering Cmd Formatting: A Quick Guide

Mastering Cmd Formatting: A Quick Guide

Fundamental CMD Commands

File and Directory Commands

A significant part of mastering CMD revolves around file and directory management.

Navigating Directories

  • cd (Change Directory): To move between directories, use the `cd` command followed by the folder path.
    cd C:\Users\YourName\Documents
    

    This command takes you directly to the Documents folder. It’s essential to know whether you are using relative paths (relative to your current location) or absolute paths (full path from the root of the drive).

Listing Files and Folders

  • dir Command: Use the `dir` command to list files and folders in the directory you are currently in.
    dir
    

    This displays all files and subdirectories. The parameters `/w` switch to a wide format while `/p` pauses the output after each screen.

Creating and Deleting Files/Folders

  • mkdir (Make Directory): To create a new folder:

    mkdir NewFolder
    

    You can create multiple folders at once by providing their names separated by spaces.

  • rmdir (Remove Directory): To remove a directory:

    rmdir NewFolder
    

    You need to use the `/s` flag if the directory is not empty:

    rmdir /s NewFolder
    

Copying and Moving Files

  • copy Command: To copy files, you can use:

    copy file1.txt file2.txt
    

    The `/y` parameter can overwrite existing files without prompting.

  • move Command: Use the move command to relocate files:

    move file1.txt C:\NewFolder
    

System Information Commands

Checking System Information

  • systeminfo: Gather a comprehensive overview of your system’s configuration:
    systeminfo
    

    This command provides details like OS version, RAM, network adapter information, and more.

Network Configuration

  • ipconfig: This command is essential for obtaining your machine’s network settings:
    ipconfig
    

    With the `/all` flag, you can see detailed information about all network interfaces:

    ipconfig /all
    

Master Cmd for Windows: Quick Tips & Tricks

Master Cmd for Windows: Quick Tips & Tricks

Advanced CMD Commands

Batch Scripting

Introduction to Batch Files

Batch files are scripts that automate a sequence of commands. They are saved with a `.bat` extension and are incredibly useful for routine tasks.

Creating a Simple Batch File

To create a batch file:

  1. Open Notepad and enter commands, such as:
    @echo off
    echo Hello, World!
    pause
    
  2. Save it as `hello.bat`. Running this file will execute the commands sequentially, displaying “Hello, World!” in the Command Prompt.

Redirecting Input and Output

Using Redirection Operators

  • Output Redirection: Utilize the `>` operator to redirect output to a file. For example:

    dir > output.txt
    

    This command saves the output of the `dir` command into `output.txt`. The `>>` operator appends to a file rather than overwriting it.

  • Input Redirection: This allows you to provide input to commands from a file using `<`. An example would be:

    sort < unsorted.txt
    

    This command sorts lines from `unsorted.txt` and displays them.

Environment Variables

What are Environment Variables?

Environment variables are dynamic values that affect the processes or programs on a computer. They can store user preference settings or system paths.

Viewing and Modifying Environment Variables

You can view all environment variables by typing:

set

To create a new variable, use:

set MY_VAR=HelloWorld

To see the value of your variable, simply type:

echo %MY_VAR%

Cmd Force Shutdown: Quick Guide to Command Line Power

Cmd Force Shutdown: Quick Guide to Command Line Power

Practical Applications of CMD

File Management Tasks

Batch Renaming Files

You can batch rename files using a loop in a batch script:

@echo off
setlocal enabledelayedexpansion
set count=1
for %%f in (*.txt) do (
    ren "%%f" "File_!count!.txt"
    set /a count=!count! + 1
)

This script renames all `.txt` files sequentially.

Searching for Files

  • findstr Command: This powerful command allows you to search inside files for specific strings:
    findstr "search term" *.txt
    

    This will search all `.txt` files in the current directory for the specified term.

Network Troubleshooting

Ping and Traceroute Commands

  • Ping: Use `ping` to check connectivity with another network device.

    ping google.com
    

    The results tell you if the ping was successful and the time it took.

  • Traceroute: The `tracert` command shows the path your data takes to reach its destination.

    tracert google.com
    

    This command displays each hop along the route, helping you identify connection issues.

System Diagnostics

Using Checksums

  • fciv or certutil: Use these to verify file integrity by generating checksums:
    certutil -hashfile C:\path\to\file.txt SHA256
    

    This command provides the SHA256 hash, allowing you to compare file integrity easily.

Mastering Cmd for Hacking: A Quick Start Guide

Mastering Cmd for Hacking: A Quick Start Guide

Conclusion

In summary, understanding CMD for Windows allows you to navigate and manage your system with flexibility and power. By mastering both the basic and more advanced commands, you can significantly enhance your efficiency and troubleshoot issues more effectively.

Next Steps for CMD Mastery

To further develop your command line skills, consider utilizing resources such as online courses, forums dedicated to CMD, and reputable books that dive deeper into this critical skill. Regular practice will make this powerful tool second nature.

Mastering Cmd For /L: A Quick Guide

Mastering Cmd For /L: A Quick Guide

Frequently Asked Questions (FAQ)

Common Issues and Troubleshooting Tips

  • Why Can’t I Execute Certain Commands?: Often, you may lack administrative privileges or the command is not recognized due to incorrect input or permissions.

  • How to Improve CMD Speed and Efficiency?: Explore hotkeys, customizing your Command Prompt (like changing colors), or diving into scripting for complex tasks.

Format Hard Drive Using Cmd: A Simple Guide

Format Hard Drive Using Cmd: A Simple Guide

Appendix

Further Learning Resources

Some excellent platforms for further learning include tech blogs, video tutorials, and coding challenges related to CMD. Consider creating practice exercises to help cement your understanding.

Командная строка Windows (CMD) — мощный инструмент, который предоставляет доступ к широкому набору команд для выполнения различных задач, от работы с файлами до настройки сети и автоматизации процессов.  В статье рассмотрим 100 популярных команд CMD, которые пригодятся как новичкам, так и опытным пользователям. Для удобства они разделены по категориям. 

Шпаргалка по CMD командам в Windows | 100 популярных команд

Разделы

  • Общие команды CMD
  • Сетевые команды CMD
  • Команды для управления процессами
  • Команды для управления файловой системой
  • Команды для управления пользователями
  • Команды для управления безопасностью
  • Команды для диагностики и устранения неполадок
  • Команды для скриптинга и автоматизации
  • Команды для управления сетевыми подключениями
  • Команды для управления печатью
  • Дополнительные команды в Windows

Общие команды командной строки (CMD) позволяют пользователям управлять ОС Windows через интерфейс командной строки. Они нацелены на различные задачи – от получения справочной информации до управления процессами. 

  • hel выводит список всех доступных команд и их краткое описание, что полезно для получения информации о базовых командах.
  • cls очищает экран командной строки. Если в окне CMD много текста, этой командой можно убрать весь вывод и начать работу «с чистого листа».
  • exit завершает текущую сессию командной строки и закрывает окно CMD.
  • echo выводит сообщения в консоль или включает/выключает отображение команд в пакетных файлах – echo Hello, World! выведет Hello, World! на экран.
  • ver отображает версию операционной системы Windows.
  • title изменяет заголовок окна командной строки. Например, title Моя Командная Строка изменит заголовок на «Моя Командная Строка».
  • pause временно приостанавливает выполнение скрипта, но при нажатии любой клавиши можно продолжить работу.
  • date позволяет узнать или изменить текущую дату в системе.
  • time отображает или изменяет текущее время в системе.
  • tasklist выводит список всех запущенных процессов с их PID (идентификатором процесса).
  • powercfg — управляет настройками энергопотребления и профилями питания. 
  • fc — сравнивает два файла и отображает их различия. 

Сетевые команды CMD

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

  • ping проверяет связь с удаленным узлом, отправляя ему пакеты данных. Например, ping google.com проверит доступность сервера Google.
  • ipconfig отображает конфигурацию сетевых интерфейсов системы (IP-адреса, маску подсети и шлюзы).
  • netstat выводит информацию о сетевых соединениях и открытых портах
  • netstat -an показывает все активные соединения.
  • tracert отслеживает маршрут пакета до целевого узла – tracert yandex.ru покажет все узлы, через которые проходит запрос.
  • nslookup используется для проверки информации о DNS-серверах.
  • nslookup example.com отображает IP-адрес сайта example.com.
  • arp выводит или изменяет записи ARP (Address Resolution Protocol) –: arp -a покажет текущие записи ARP.
  • route управляет таблицей маршрутизации сети – route print выведет все существующие маршруты в системе.
  • net use подключает сетевые диски. Например, net use Z: \\server\folder подключит сетевой ресурс как диск Z:.
  • netsh позволяет настраивать различные параметры сети через командную строку.
  • netsh wlan show profiles отображает сохраненные профили Wi-Fi.

Команды для управления процессами

Команды ниже позволяют эффективно управлять процессами и службами на вашем ПК: помогают запускать службы, планировать задачи, управлять активными процессами, а также выключать или перезагружать систему. С их помощью можно автоматизировать выполнение задач, получать информацию о состоянии системы и контролировать её работоспособность. 

  • sc управляет службами Windows. Пример: sc start servicename запустит службу с именем servicename.
  • schtasks управляет планировщиком задач. Так, schtasks /create /tn «Моя Задача» /tr notepad.exe /sc once /st 12:00 создаст задачу для запуска.
  • start запускает программу или команду в новом окне. Например, start notepad откроет блокнот.
  • wmic взаимодействует с системой через Windows Management Instrumentation – wmic process list brief покажет список процессов.
  • shutdown выключает, перезагружает или завершает работу системы. Так, shutdown /s /f /t 0 немедленно выключит компьютер.
  • systeminfo выводит информацию о системе, включая версию Windows, параметры оборудования и установленные обновления.

Команды для управления файловой системой

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

  • dir отображает список файлов и каталогов в указанной директории. Пример: dir C:\Windows выведет содержимое папки Windows.
  • cd меняет текущий каталог. Так, cd C:\Users перейдет в папку пользователей.
  • md NewFolder создает новую папку. 
  • rd удаляет пустую папку. Пример: rd NewFolder удалит папку NewFolder.
  • copy копирует файлы из одного места в другое.
  • move перемещает файлы или папки.
  • del удаляет файлы. Например, del file.txt удалит файл file.txt.
  • xcopy копирует файлы и директории, включая их структуру. Так, xcopy C:\Source D:\Destination /s /e скопирует все файлы и папки из Source в Destination.
  • robocopy более продвинутая версия xcopy, используется для надежного копирования данных. Например, robocopy C:\Source D:\Destination /mir синхронизирует две папки.

Команды для управления пользователями

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

  • net user управляет учетными записями пользователей.
  • net user UserName /add добавляет нового пользователя с именем UserName.
  • net localgroup управляет локальными группами пользователей.
  • net localgroup Administrators UserName /add добавляет пользователя в группу администраторов.
  • whoami выводит имя текущего пользователя и информацию о его правах.
  • runas позволяет запускать программы от имени другого пользователя. Так, runas /user:administrator cmd запустит CMD с правами администратора.
  • net accounts управляет параметрами учетных записей, например, минимальной длиной пароля и периодом его действия.
  • gpupdate — обновляет групповые политики на локальном компьютере, что полезно для администраторов, управляемых сетей.
  • taskview — открывает таймлайн Windows, показывая историю активности пользователя, полезно для управления и поиска ранее использованных файлов и приложений.
  • msg отправляет сообщение пользователям, подключенным к системе. Пример: msg «Система будет перезагружена через 5 минут» отправит сообщение всем пользователям.

Команды для управления безопасностью

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

  • cipher управляет шифрованием файлов на дисках NTFS.
  • cipher/e зашифровывает файлы в указанной директории.
  • sfc проверяет целостность системных файлов и автоматически восстанавливает их при обнаружении повреждений.
  • sfc /verifyonly — проверяет системные файлы на наличие повреждений, но не исправляет их автоматически.
  • sfc /scannow выполняет полную проверку системы.
  • cacls изменяет права доступа к файлам. Пример: cacls file.txt /g UserName:F даст пользователю полный доступ к файлу.
  • icacls расширяет возможности команды cacls и предоставляет дополнительные параметры для управления правами доступа.
  • takeown позволяет взять владение файлом или директорией. Так, takeown /f file.txt предоставит доступ к файлам.
  • attrib изменяет атрибуты файлов и папок. Например, attrib +r file.txt сделает файл доступным только для чтения.

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

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

  • chkdsk проверяет диск на наличие ошибок и исправляет их. Так, chkdsk C: /f выполнит проверку диска C.
  • bootrec восстанавливает загрузочный сектор. 
  • bcdedit управляет параметрами загрузки системы. 
  • bcdedit /set {current} safeboot minimal включает безопасный режим.

Команды для скриптинга и автоматизации

Команды, приведенные ниже, предназначены для создания сложных сценариев выполнения команд, что позволяет автоматизировать повседневные задачи и более эффективно управлять процессами. 

  • for создает цикл для выполнения команд. Например, for %i in (1 2 3) do echo %i выведет числа 1, 2, 3.
  • if выполняет условное выполнение команд.
  • goto перенаправляет выполнение скрипта к определенной метке.
  • call вызывает другую команду или скрипт.

Команды для управления сетевыми подключениями

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

  • ipconfig /release освобождает текущий IP-адрес, назначенный DHCP сервером, что позволяет при необходимости сбросить сетевое подключение.
  • ipconfig /renew обновляет IP-адрес, полученный от DHCP сервера. Часто используется после команды ipconfig /release для восстановления подключения.
  • ipconfig /flushdns очищает кэш DNS, если изменился DNS-сервер или необходимо устранить проблемы с доступом к сайтам.
  • ipconfig /displaydns выводит содержимое кэша DNS, часто используется для диагностики проблем с DNS.
  • netsh interface ip set address используется для назначения статического IP-адреса сетевому интерфейсу. Пример: netsh interface ip set address Ethernet static 192.168.1.100 255.255.255.0 192.168.1.1.
  • netsh wlan show drivers выводит информацию о драйверах беспроводной сети, что полезно при настройке Wi-Fi подключения.
  • netsh wlan show interfaces отображает текущие активные беспроводные подключения и их параметры, например, мощность сигнала.
  • netsh wlan connect подключает к указанной Wi-Fi сети. Для этого нужно ввести: netsh wlan connect name=MyWiFi.
  • netsh wlan disconnect отключает текущее беспроводное подключение.
  • netsh advfirewall set allprofiles state управляет состоянием брандмауэра Windows – netsh advfirewall set allprofiles state off отключает брандмауэр для всех профилей.
  • netsh int ip reset сбрасывает настройки IP стека (TCP/IP) к значениям по умолчанию, помогая при сетевых неполадках.
  • route add добавляет маршрут в таблицу маршрутизации. Например, route add 192.168.2.0 mask 255.255.255.0 192.168.1.1 добавит маршрут для подсети 192.168.2.0 через шлюз 192.168.1.1.
  • route delete удаляет указанный маршрут из таблицы маршрутизации.
  • netsh interface show interface выводит список всех сетевых интерфейсов в системе, включая их состояние и тип.
  • net view отображает список компьютеров в локальной сети – net view \\server покажет общие ресурсы на указанном сервере.
  • net use /delete удаляет существующее подключение к сетевому ресурсу. Так, net use Z: /delete отключает сетевой диск Z:.
  • ftp открывает FTP-клиент для передачи файлов между локальной и удаленной системами. Например, по команде ftp ftp.example.com ПК подключится к FTP-серверу.
  • telnet используется для подключения к удаленным системам через Telnet-протокол. Так, telnet example.com 23 подключит ПК к серверу на порту 23.
  • getmac выводит MAC-адреса всех сетевых интерфейсов компьютера.

Команды для управления печатью

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

  • print отправляет файл на печать. Например, print C:\Documents\file.txt отправит текстовый файл на принтер по умолчанию.
  • rundll32 printui.dll,PrintUIEntry открывает диалоговое окно для установки или управления принтерами – rundll32 printui.dll,PrintUIEntry /in /n\\server\printer установит сетевой принтер.
  • net print отображает список заданий на печать – net print \\server\printer покажет очередь печати на указанном принтере.
  • net stop spooler останавливает службу диспетчера очереди печати (spooler), особенно когда требуется устранить зависшие задания печати.
  • net start spooler запускает службу диспетчера очереди печати после её остановки.
  • wmic printer list brief выводит список установленных принтеров с краткой информацией о каждом из них.
  • wmic printer where default=true get name выводит имя принтера, установленного по умолчанию.
  • wmic printer where name=’PrinterName’ delete удаляет указанный принтер из системы.
  • wmic printerconfig отображает информацию о конфигурации принтера, включая его настройки и параметры печати.
  • cscript prnjobs.vbs используется для управления заданиями печати через скрипт prnjobs.vbs, который можно использовать для удаления, приостановки или возобновления заданий.

Дополнительные команды в Windows

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

  • wevtutil управляет журналами событий Windows. Например, wevtutil qe System выведет события из системного журнала.
  • tzutil управляет настройками часовых поясов. tzutil /s Pacific Standard Time установит часовой пояс на Тихоокеанское стандартное время.
  • taskkill — завершает процесс по его PID или имени. Так, taskkill /F /PID 1234 завершит процесс с PID 1234.
  • powercfg /hibernate off — отключает режим гибернации.
  • powercfg /energy — создает отчет об использовании энергии системой.

The Windows Command Prompt (CMD) is a powerful tool that allows users to interact with their operating system through text-based commands. Whether you’re a beginner exploring CMD for the first time, an expert troubleshooting advanced issues, or just looking for utility-focused tasks, this guide has you covered.

In this guide, we will provide you with some of the most useful commands for the following:

  • CMD Commands for Beginners
  • CMD Commands for Experts
  • CMD Commands for Utility
  • CMD Commands for Troubleshooting
  • CMD Commands for Students
  • CMD Commands for Programmers

CMD Commands for Beginners

These commands are essential for users who are new to CMD and provide basic functionalities to help them navigate and perform simple tasks.

1. View Directory ‘dir

  • Function: Displays the contents of the current directory.
  • How to use: Type dir and press Enter. Use dir /s to include subdirectories.
  • Use case: Quickly view files and folders in your current location.
Syntax: dir

2. Change Directories ‘cd’

  • Function: Lets you navigate between folders.
  • How to use: Type cd [folder_name] to move into a directory. Use cd .. to go up one level.
  • Use case: Navigate to specific directories to manage files or execute commands
Syntax: cd [folder name]

3. Create a New Directory ‘mkdir’ or ‘md’

  • Function: Allows you to create a new directory
  • How to use: Type mkdir [file_name]– Here the new directory name is GFG
  • Use case: When you need a new directory for any separate work, you may create a new directory
Syntax: mkdir [GFG]

4. Rename a File ‘ren’

  • Function: Helps in renaming any file or directory.
  • How to use: Type ren or rename [old_name] [new_name] and press Enter.
  • Use case: Discover new method of renaming file or any directory.
Syntax: ren xyz.txt newxyz.txt

5. Delete a File ‘del’

  • Function: Lets you to remove one or more files
  • How to use: Type del [file_name]– This will erase the provided file name
  • Use case: This function allows you to erase any file if you’re unable to fetch
Syntax: del[file_name]

6. Close ‘exit’

  • Function: Closes the Command Prompt window.
  • How to use: Type exit and press Enter.
  • Use case: Ends your session with CMD.
Syntax: exit

7. Clear Screen ‘cls’

  • Function: Clears all text from the CMD window.
  • How to use: Type cls and press Enter.
  • Use case: Removes clutter after multiple commands
Syntax: cls

8. View Available Command ‘help’

  • Function: Lists all available commands and their descriptions.
  • How to use: Type help and press Enter.
  • Use case: Discover new commands and learn their functions.
Syntax: help

9. Display or Set the System time ‘time’

  • Function: Lets you set the system time or display the current time.
  • How to use: Type time [new_time] and press Enter.
  • Use case: Allows the user to set their system’s time without additional navigation
Syntax: time [new_time]

10. Copy Files ‘copy’

  • Function: Lists all available commands and their descriptions.
  • How to use: Type copy [source1] [destination2] and press Enter.
  • Use case: Discover new commands and learn their functions.
Syntax: copy file.txt Backup\
Command Description Syntax Example
dir View the contents of a directory dir dir C:\Users\Documents
cd Change the current working directory cd [directory_name] cd Downloads
mkdir Create a new directory mkdir [directory_name] mkdir NewProject
ren Rename a file ren [old_name] [new_name] ren draft.txt final.txt
del Delete a file del [file_name] del unwanted.txt
exit Close the Command Prompt exit exit
cls Clear the Command Prompt screen cls cls
help View available CMD commands and their descriptions help help
time Display or set the system time time time 14:30:00
copy Copy files from one location to another copy [destination] copy report.docx D:\Backup\

CMD Commands for Experts

These commands are more advanced and suitable for users comfortable with troubleshooting and system management tasks.

1. System File Checker ‘sfc’

  • Function: Scans and repairs corrupted system files.
  • How to use: Type sfc /scannow in CMD (run as administrator).
  • Use case: Fix system errors related to missing or corrupted files.
Syntax: sfc /scannow

2. Disk Error ‘chkdsk’

  • Function: Scans the hard drive for bad sectors and file system errors.
  • How to use: Type chkdsk [drive letter]: /f (e.g., chkdsk C: /f) in CMD.
  • Use case: Identify and fix disk issues.
Syntax: chkdsk C: /f

3. View Running Processor ‘tasklist’

  • Function: Displays all running processes and their details.
  • How to use: Type tasklist to list processes. Use tasklist /fi "imagename eq [process name]" to filter.
  • Use case: Identify resource-heavy or unresponsive processes.
Syntax: tasklist /fi "imagename eq [process name]

4. Restart ‘shutdown’

  • Function: Allows you to shut down or restart the computer via CMD.
  • How to use:
    • Shutdown: shutdown /s /f /t [seconds].
    • Restart: shutdown /r /f /t [seconds].
  • Use case: Automate shutdown or restart tasks
Syntax: 
Shutdown: shutdown /s /f /t [seconds].
Restart: shutdown /r /f /t [seconds].

5. Network Statistics ‘netstat’

  • Function: Displays active connections and listening ports.
  • How to use: Type netstat to view all active connections.
  • Use case: Diagnose network-related issues or monitor network activity.
Syntax: netstat

6. Kill a Running Process ‘taskkill’

  • Function: Lets you terminate a process using its process ID (PID)
  • How to use: Type taskkill /[PID] /F to terminate
  • Use case: Can be helpful for terminating any dedicated PID.

Example (PID: 1124)

Syntax: taskkill /PID 11234 /F

7. View Saved Passwords ‘netsh wlan show profiles’

  • Function: Retrieve the password of a saved Wi-Fi network.
  • How to use: Type netsh wlan show profile name=”WiFi-Name” key=clear
  • Use case: Discover new commands and learn their functions.
Example: netsh wlan show profile name="MyHomeWiFi" key=clear
Command Description Syntax Example
sfc System File Checker – Scans and repairs system files sfc /scannow sfc /scannow
chkdsk Check Disk – Scans and fixes disk errors chkdsk [drive]: /f /r chkdsk C: /f /r
tasklist View running processes tasklist tasklist
shutdown Shutdown or restart the system shutdown /r /t [seconds] shutdown /r /t 10 (Restart in 10 seconds)
netstat View network statistics and active connections netstat -a netstat -an (Show all connections numerically)
taskkill Kill a running process using its process ID (PID) taskkill /PID [PID] /F taskkill /PID 4567 /F (Kill process with ID 4567)
netsh wlan show profiles View saved Wi-Fi network names netsh wlan show profiles netsh wlan show profiles

CMD Commands for Utility

These commands are focused on specific tasks and utilities to enhance productivity and system performance.

1. Network Configuration ‘ipconfig’

  • Function: Displays IP address, subnet mask, and gateway information.
  • How to use:
    • Basic: Type ipconfig.
    • Detailed: Type ipconfig /all.
  • Use case: Troubleshoot internet connectivity issues.
Syntax: ipconfig

2. Network Connectivity ‘ping’

  • Function: Sends packets to test communication with another device or website.
  • How to use: Type ping [destination] 
  • Use case: Check if a device or website is reachable.
Syntax: ping geeksforgeeks.org

3. System Information ‘systeminfo’

  • Function: Displays detailed information about your computer.
  • How to use: Type systeminfo.
  • Use case: Quickly access system specifications for troubleshooting or reporting.
Syntax: systeminfo

4. Trace Route ‘tracert’

  • Function: Shows the path packets take to reach a specific destination.
  • How to use: Type tracert [destination]
  • Use case: Identify network bottlenecks or connectivity issues.
Syntax: tracert geeksforgeeks.org

5. Manage Drives ‘diskpart’

  • Function: Opens a command-line utility for managing disk partitions.
  • How to use: Type diskpart to enter the disk management interface.
  • Use case: Create, delete, or modify partitions on your drives.
Syntax: diskpart

6. Delete a Directory ‘rmdir’

  • Function: Removes directory from the origin
  • How to use: Type rmdir [directory_name] and press Enter.
  • Use case: Discover new commands and learn their functions.

Example: GFG – Directory name

Syntax: rmdir GFG

7. View ‘rmdir’

  • Function: Removes directory from the origin
  • How to use: Type rmdir [directory_name] and press Enter.
  • Use case: Discover new commands and learn their functions.
Example: GFG - Directory name

8. Manage User Account ‘net user’

  • Function: To list all the user accounts
  • How to use: Type net user and press Enter.
  • Use case: Discover new commands and learn their functions.
Syntax: net user username password /add

9. View Startup Programs ‘wmic startup get caption,command’

  • Function: To check what programs launch on startup.
  • How to use: Type wmic startup get caption,command, and press Enter.
  • Use case: Discover new commands and learn their functions.
Syntax: wmic startup get caption,command
Command Description Syntax Example
ipconfig View network configuration, including IP address, subnet mask, and gateway ipconfig ipconfig /all (Displays detailed network info)
ping Test network connectivity by sending packets to a host ping [host or IP] ping google.com (Check connection to Google)
systeminfo Display detailed system information, including OS version, installed memory, and processor systeminfo systeminfo
tracert Trace the route packets take to a network destination tracert [hostname or IP] tracert google.com (View network path to Google)
diskpart Manage disk partitions, including creating, formatting, and deleting partitions diskpart diskpart → list disk → select disk 1 → create partition primary
rmdir Delete a directory (folder) rmdir [directory_name] rmdir /s /q OldFolder (Delete a folder and its contents without confirmation)
dir View contents of a directory dir dir C:\Users\Documents (List files in a specific directory)
net user Manage user accounts, including adding, modifying, or deleting users net user net user John password123 /add (Create a new user account)
wmic startup get caption,command View startup programs and their commands wmic startup get caption,command wmic startup get caption,command

CMD Commands for Troubleshooting

1. File Comparison ‘fc’

  • Function: Compares two files and highlights differences.
  • How to use: Type fc [file1] [file2] to compare files.
  • Use case: Detect changes or errors in files
Syntax: fc 1 2

2. Advanced Network Diagnostics ‘pathping’

  • Function: Combines ping and tracert functionalities to provide detailed network path diagnostics.
  • How to use: Type pathping [destination]
  • Use case: Troubleshoot complex network issues.
Syntax: pathping geeksforgeeks.org

3. Registry Editor ‘regedit’

  • Function: Launches the Windows Registry Editor.
  • How to use: Type regedit to open the registry.
  • Use case: Modify registry keys for advanced configuration or troubleshooting.
Syntax: regedit

4. View MAC ‘getmac’

  • Function: Displays the MAC address of your network adapter.
  • How to use: Type getmac to view the MAC address.
  • Use case: Identify your device’s hardware address for network configurations
Syntax: getmac

5. Power Configuration ‘powercfg’

  • Function: Displays and manages power settings.
  • How to use: Type powercfg /[option] 
  • Use case: Optimize power usage and troubleshoot battery issues.
Syntax: powercfg /energy for a detailed power usage report

6. Enable Boot Manager ‘bcdedit’

  • Function: Used to modify boot configuration settings
  • How to use: Type bcdedit / set current
  • Use case: Discover new commands and learn their functions.
Syntax: bcdedit /set {current} bootmenupolicy standard

7. Format a Drive ‘format’

  • Function: To erase any specific drive.
  • How to use: Type format [drive]: /FS:NTFS and press Enter.
  • Use case: Discover new commands and learn their functions.
Syntax: format D: /FS:NTFS
Command Description Syntax Example
fc Compare two files and highlight differences fc [file1] [file2] fc file1.txt file2.txt (Compare two text files)
pathping Perform advanced network diagnostics with packet loss details pathping [destination] pathping google.com (Analyze network route to Google)
regedit Open the Windows Registry Editor (GUI) regedit regedit (Opens the registry editor – use with caution!)
getmac Display the MAC (Media Access Control) address of your network adapters getmac getmac /v /fo list (View MAC addresses in detailed format)
powercfg Manage and analyze power configurations powercfg /[option] powercfg /batteryreport (Generate a battery usage report)
bcdedit Enable, disable, or modify Windows Boot Configuration bcdedit /set {current} [option] bcdedit /set {current} bootmenupolicy standard (Enable boot menu in Windows 10/11)
format Format a drive (erase all data) format [drive]: /FS:[filesystem] format D: /FS:NTFS (Format drive D: with NTFS file system)

CMD Commands for Students

Students can use these commands to manage files, perform simple calculations, and even help with tasks like coding and studying.

1. Calculator ‘calc’

  • Function: Opens the Windows Calculator application.
  • How to use: Type calc and press Enter.
  • Use case: Quickly open the calculator for
Syntax: calc

CMD Commands for Programmers

Programmers often use CMD to automate tasks, compile code, and test network functionality. These commands can be especially useful for developers working in command-line environments.

1. Compile Java Code ‘javac’

  • Function: Compiles Java source files into bytecode.
  • How to use: Type javac [file name].java to compile Java code.
  • Use case: Compile and test Java programs directly from the command line.
Syntax: javac

2. Version Control ‘git’

  • Function: Interacts with Git repositories from the command line.
  • How to use: Type git [command]
  • Use case: Manage version control, clone repositories, or push commits from the command line.
Syntax: git clone [repository URL]

3. Execute Python Script ‘python’

  • Function: Runs Python scripts in the command prompt.
  • How to use: Type python [script.py] to execute a Python program.
  • Use case: Test and run Python code directly in the command line.
Syntax: python [script.py]

4. Run Node.js Scripts ‘node’

  • Function: Executes Node.js scripts.
  • How to use: Type node [script.js] to run a JavaScript file using Node.js.
  • Use case: Run backend scripts and test JavaScript programs in the command line.
Syntax: node [script.js]

5. Node Package Manager ‘npm’

  • Function: Installs and manages JavaScript packages.
  • How to use: Type npm install [package] to install a package.
  • Use case: Manage dependencies and libraries in Node.js applications.
Syntax: npm install [package]
Command Description Syntax Example
javac Compile Java source code into bytecode (.class files) javac [filename].java javac HelloWorld.java (Compile a Java file)
git Version control system for tracking changes in files git [command] git clone https://github.com/user/repo.git (Clone a repository)
python Execute a Python script or enter interactive mode python [script.py] python script.py (Run a Python script)
node Execute JavaScript code using Node.js node [script.js] node app.js (Run a Node.js script)
npm Manage Node.js packages and dependencies npm [command] npm install express (Install the Express.js package)

Bonus: CMD Tricks and Tips

To make CMD usage even more efficient, here are some bonus tips:

1. Save CMD Output to a File

Use the > operator to save the output of a command to a text file.

2. Open CMD in a Specific Directory

Instead of navigating manually, you can directly open CMD in a folder by typing cmd in the File Explorer’s address bar.

3. Use && for Multiple Commands

You can run multiple commands sequentially:

ipconfig && ping google.com

Conclusion

Mastering the most useful CMD commands in Windows can empower you to perform tasks more efficiently, troubleshoot problems, and gain deeper control over your system. By familiarizing yourself with these essential CMD commands, you’ll be better equipped to handle a variety of situations, from simple file management to advanced system configurations. Whether you’re a beginner or an experienced user, these commands are invaluable tools to have at your disposal.

Команда FOR задает запуск некоторой команды для каждого файла из заданного множества.

Работу команды for можно охарактеризовать так:

a) получение диапазона данных
b) присвоить переменной цикла for (например %%G) значение из диапазона данных
c) выполнить команду (иногда в команде участвует %%G, например, в качестве параметра)
d) выполнить шаги a), b), c), пока не будет достигнуто конечное значение из диапазона значений переменной цикла.

Очень хорошо команда for описана в справке w2k.

Синтаксис

for {% | %%}< переменная > in (< множество >) do < команда > [< ПараметрыКоманднойСтроки > ]

Параметры команды for следующие:

Параметр Описание
{%% | %}< переменная > Обязательный элемент, который представляет замещаемое значение. Используйте один знак %, чтобы выполнить команду for из командной строки (не в командном файле). Два знака %% используются для команды for, выполняемой в составе командного файла (*.bat или *.cmd). Имена переменных чувствительны к регистру символов, и должны быть составлены из символов букв алфавита (например %a, %b или %c).
(< множество >) Обязательный элемент, указывает на один или несколько файлов, каталогов или текстовых строк, или диапазон значений, по которому должна проходить итерация команды for. Наличие круглых скобок обязательно.
< команда > Обязательный элемент, который указывает команду, выполняемого для каждого элемента множества (см. предыдущий параметр).
ПараметрыКоманднойСтроки Задает параметры командной строки, необходимые для использования с указанной командой (см. предыдущий параметр).
/? Отображение справки в командной строке для команды for.

Команду for можно использовать в командном файле (*.bat, *.cmd) или непосредственно запускать в командной строке.

Атрибуты. К команде for применяются перечисленные ниже атрибуты.

• В команде for переменная %переменная (или %%переменная) будет заменяться текстовой строкой из заданного параметра множество, пока параметр команда не обработает все файлы этого множества.
• Имена параметров переменная команды for учитывают регистр буквы, они являются глобальными, и одновременно может быть активно не больше 52 переменных.
• Для обозначения параметра переменная можно использовать любые знаки, кроме цифр 0–9, чтобы не было конфликта с параметрами пакетных файлов %0–%9. Для простых пакетных файлов вполне достаточно обозначений с одним знаком, например %%f.
• В сложных командных файлах могут быть использованы и другие обозначения для параметра переменная.

Задание множества файлов. Параметр множество может представлять группу файлов или несколько групп файлов. Для задания групп файлов можно использовать подстановочные знаки (* и ?). Следующие множества файлов являются допустимыми:

(*.doc)
(*.doc *.txt *.me)
(jan*.doc jan*.rpt feb*.doc feb*.rpt)
(ar??1991.* ap??1991.*)

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

in и do. Ключевые слова in и do не являются параметрами, но они требуются для работы команды for. Если какое-то из этих слов пропущено, на экран будет выведено сообщение об ошибке.

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

• Только каталоги

Если параметр множество содержит подстановочные знаки (* и ?), команда, указанная в параметре команда, выполняется для каждого каталога (кроме множества файлов в указанном каталоге), совпадающего с параметром множество. Используется следующий синтаксис.
for /D {%% | %}переменная in (множество) do команда [ПараметрыКоманднойСтроки]

• Рекурсивная

Проходит по дереву каталогов с корнем в [диск:]путь, выполняя инструкцию for для каждого каталога в дереве. Если после ключа /R не задан каталог, предполагается текущий каталог. Если параметр множество задан одной точкой (.), то команда просто перечислит каталоги в дереве. Используется следующий синтаксис.
for /R [[диск:]путь] {%% | %}переменная in (множество) do команда [ПараметрыКоманднойСтроки]

• Итерация диапазона значений

Используйте переменную итерации для установки начального значения (НачальноеЗначение#), а затем перемещайтесь по диапазону значений, пока значение не превысит конечное значение множества (КонечноеЗначение#). /L выполнит итерацию, сравнив параметр НачальноеЗначение# с параметром КонечноеЗначение#. Если параметрНачальноеЗначение# меньше параметра КонечноеЗначение#, то выполняется команда. Когда переменная итерации превысит параметр КонечноеЗначение#, командная оболочка покидает цикл. Также можно использовать отрицательный параметр шаг# для перемещения в диапазоне убывающих значений. Например, (1,1,5) создает последовательность «1 2 3 4 5», а (5,-1,1) создает последовательность «5 4 3 2 1». Используется следующий синтаксис.
for /L {%% | %}переменная in (НачальноеЗначение#,шаг#,КонечноеЗначение#) do команда [ПараметрыКоманднойСтроки]

• Итерация и разбор файлов

Разбор файлов следует использовать для обработки вывода команды, строк и содержимого файла. Используйте переменные итерации для определения содержимого или строк, которые требуется проверить. Параметр КлючевыеСловаРазбора используется для изменения разбора. Используйте параметр маркера КлючевыеСловаРазбора для указания маркеров, которые воспринимаются как переменные итерации. Примечание. Без параметра маркера ключ /F проверяет только первый маркер.

Разбор файлов состоит в чтении вывода, строки или содержимого файла, разбиении его на отдельные строки текста и разборе каждой строки на ноль или маркеры. Цикл программы for затем вызывается с переменной итерации, установленной в маркер. По умолчанию /F передает первый отделенный пробелом элемент из каждой строки каждого файла. Пустые строки пропускаются. Используется также другой синтаксис.
for /F [«КлючевыеСловаРазбора»] {%% | %}переменная lin (МножествоИменФайлов) do команда [ПараметрыКоманднойСтроки]
for /F [«КлючевыеСловаРазбора»] {%% | %}переменная in («СимвольнаяСтрока») do команда [ПараметрыКоманднойСтроки]
for /F [«КлючевыеСловаРазбора»] {%% | %}переменная in (‘команда’) do команда [ПараметрыКоманднойСтроки]

Аргумент МножествоИменФайлов задает одно или несколько имен файлов. Каждый файл открывается, считывается и обрабатывается до перехода к следующему файлу параметра МножествоИменФайлов. Чтобы переопределить стандартное поведение разбора, укажите параметр «КлючевыеСловаРазбора». Это строка, заключенная в кавычки, которая содержит одно или несколько ключевых слов для указания различных режимов разбора.

Если используется параметр usebackq, используйте один из приведенных ниже синтаксисов:
for /F [«usebackqКлючевыеСловаРазбора»] {%% | %}переменная in («МножествоИменФайлов») do команда [ПараметрыКоманднойСтроки]
for /F [«usebackqКлючевыеСловаРазбора»] {%% | %}переменная in (‘СимвольнаяСтрока’) do команда [ПараметрыКоманднойСтроки]
for /F [«usebackqКлючевыеСловаРазбора»] {%% | %}переменная in (‘команда’) do команда [ПараметрыКоманднойСтроки]

В приведенной ниже таблице перечислены ключевые слова разбора, которые используются для параметра КлючевыеСловаРазбора.

Ключевое слово Описание
eol=c Задает символ конца строки (только один символ).
skip=N Задает число строк, пропускаемых в начале файла.
delims=xxx Задает набор разделителей. Заменяет набор разделителей по умолчанию, состоящий из пробела и символа табуляции.
tokens=X,Y,M-N Задает элементы, передаваемые из каждой строки в тело цикла for при каждой итерации. В результате размещаются дополнительные имена переменных. Форма M-N задает диапазон, указывающий элементы с M-го по N-ый. Если последним символом строки tokens= является звездочка (*), то размещается дополнительная переменная, в которую помещается остаток строки после разбора последнего элемента.
usebackq Задает возможность использования кавычек для имен файлов в параметре МножествоИменФайлов. Задает исполнение строки, заключенной в обратные кавычки, как команды, а строки в одиночных кавычках — как команды в символьной строке.

• Подстановка переменных

Были расширены модификаторы подстановок для ссылок на переменные в for. Приведенная ниже таблица перечисляет варианты синтаксических конструкций (на примере переменной I).

Переменная с модификатором Описание
%~I Расширение %I, которое удаляет окружающие кавычки («»).
%~fI Расширение %I до полного имени пути.
%~dI Замена %I именем диска.
%~pI Замена %I на путь.
%~nI Замена %I одним именем файла.
%~xI Замена %I расширением имени файла.
%~sI Замена путем, содержащим только короткие имена.
%~aI Замена %I атрибутами файла.
%~tI

Замена %I временем модификации файла.

%~zI Замена %I размером файла.
%~$PATH:I Поиск в каталогах, перечисленных в переменной среды PATH, и замена %I полным именем первого найденного файла. Если переменная среды не определена или поиск не обнаружил файлов, модификатор выдает пустую строку.

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

Переменная с объединенными модификаторами Описание
%~dpI Замена %I именем диска и путем.
%~nxI Замена %I именем файла и расширением.
%~fsI Замена %I полным именем пути с короткими именами.
%~dp$PATH:I Поиск в каталогах, перечисленных в переменной среды PATH, и замена %I именем диска и путем первого найденного файла.
%~ftzaI Замена %I строкой, аналогичной результату работы команды dir.

В приведенных выше примерах %I и PATH могут быть заменены другими допустимыми значениями. Допустимое имя переменной for прекращает синтаксис %~.

Использование прописных букв в именах переменных, например %I, может улучшить восприятие программы и позволит избежать недоразумений с модификаторами, в которых строчные и прописные буквы не различаются.

Разбор строки. Конструкция for /F может быть использована непосредственно для строки. Для этого поместите параметр МножествоИменФайлов между скобками в одиночные кавычки (‘МножествоИменФайлов’). Параметр МножествоИменФайлов будет воспринят как одиночная строка ввода из файла и будет разобран.

Разбор вывода. Команду for /F можно использовать для разбора вывода команды. Для этого поместите параметр МножествоИменФайлов между скобками в обратные кавычки. Он будет воспринят как командная строка, которая передается дочернему интерпретатору командной строки Cmd.exe, а результаты работы команды помещаются в памяти и разбираются, как если бы они являлись файлом.

[Примеры]

В пакетных файлах используется следующий синтаксис для команды for:
for %%переменная in (множество) do команда [ПараметрыКоманднойСтроки]

Чтобы отобразить содержимое всех файлов, имеющих разрешение DOC или TXT, в текущем каталоге с помощью заменяемой переменной %f, введите следующую команду:
for %%f in (*.doc *.txt) do type %%f

В предыдущем примере каждый файл с расширением .doc или .txt в текущем каталоге будет подставляться вместо переменной %f, пока не будет выведено содержимое всех файлов. Для использования этой команды в пакетном файле нужно заменить каждую команду %f на %%а. В противном случае переменная игнорируется и выводится сообщение об ошибке.

Чтобы произвести разбор файла, игнорируя комментарии, можно использовать следующую команду:
for /F «eol=; tokens=2,3* delims=,» %i in (myfile.txt) do @echo %i %j %k

Данная команда производит разбор каждой строки в файле Myfile.txt, игнорируя строки, начинающиеся с точки с запятой, и передает второй и третий элементы из каждой строки в тело цикла команды FOR. Элементы разделяются запятыми или пробелами. Тело инструкции FOR использует %i для получения второго элемента, %j для получения третьего элемента и %k для получения оставшихся элементов в строке. Если имена файлов содержат пробелы, их следует заключать в кавычки (например, «ИмяФайла»). Для использования кавычек необходима команда usebackq. В противном случае кавычки рассматриваются как определение символьной строки для разбора.

Переменная %i объявлена явно в инструкции FOR. Переменные %j и %k объявлены явно при использовании tokens=. С помощью tokens= можно указать до 26 элементов, если это не вызовет попытки объявить переменную с именем, большим буквы «z» или «Z».

Для разбора вывода команды с помощью помещения параметра МножествоИменФайлов в скобки можно использовать следующую команду (пример выводит список имен всех переменных окружения):
for /F «usebackq delims==» %i IN (`set`) DO @echo %i

Ищем в директориях файлы с расширением html содержащие строку google:
for /R %%f in (*.html) do @findstr /m «google» %%f

FOR /L
выполнить команду для диапазона чисел
Синтаксис
FOR /L %%parameter IN (start,step,end) DO command

Где
   start      первое число (включительно)
   step       инкремент числа для каждого шага
   end        последнее число (включительно)
   command    выполняемая команда, здесь же указываются параметры командной строки для неё
   %%parameter изменяемый при каждой прокрутке цикла параметр (переменная цикла)

Внутри командного файла в качестве параметра используйте %%G, а в командной строке %G (такие уж Микрософт придумал правила). (20,-5,10) будет генерить последовательность 20 15 10, а (1,1,5) последовательность 1 2 3 4 5.

Пример
FOR /L %%G IN (1,1,5) DO echo %%G

Можно использовать нечисловой список, например:
FOR %%G IN (Sun Mon Tue Wed Thur Fri Sat) DO echo %%G

[Другие команды for]

FOR — цикл по всем файлам в одной директории (исключая её подкаталоги)
FOR /R — цикл по всем файлам, включая подкаталоги
FOR /D — цикл через несколько папок
FOR /F — цикл через слова в текстовом файле или через вывод команды

syntax-FOR-Files
     FOR %%parameter IN (set) DO command
syntax-FOR-Files-Rooted at Path
     FOR /R [[drive:]path] %%parameter IN (set) DO command
syntax-FOR-Folders
     FOR /D %%parameter IN (folder_set) DO command
syntax-FOR-List of numbers
     FOR /L %%parameter IN (start,step,end) DO command
syntax-FOR-File contents
     FOR /F [«options»] %%parameter IN (filenameset) DO command
     FOR /F [«options»] %%parameter IN («Text string to process») DO command
syntax-FOR-Command Results
     FOR /F [«options»] %%parameter IN (‘command to process’) DO command

[Связанные с for команды]

FORFILES (w2003 Server) — выборка списка файлов из директории для отображения или использования при обработке в bat-файле
GOTO метка — прямой переход на строку в командном файле, помеченную строкой :метка
IF — условное выполнение команды

[Equivalent Linux BASH commands]

for — Expand words, and execute commands
case — Conditionally perform a command
eval — Evaluate several commands/arguments
if — Conditionally perform a command
gawk — Find and Replace text within file(s)
m4 — Macro processor
until — Execute commands (until error)
while — Execute commands

[Условные обозначения форматирования]

Формат Описание
Курсив Сведения, вводимые пользователем
Полужирный шрифт Элементы, вводимые без изменений
Многоточие (…) Параметр может быть введен в командной строке несколько раз
В квадратных скобках ([]) Необязательные элементы
В фигурных скобках ({}), варианты, разделенные вертикальной линией (|). Пример: {even|odd} Набор вариантов, из которых необходимо выбрать один
Courier font Программа или выходные данные

[Ссылки]

1. Практические приемы программирования в bat-файлах.

When working on the Windows command line, do you remember how often you kept looking for the same commands? Do you easily mistype in the Windows command prompt as if you were using bash commands, such as “rm” instead of “del”? If you’ve ever been in the situations above, this Windows command line cheat sheet is for you.

The Windows command line is only as powerful as the commands at your disposal, which we’ll expand on in this Windows command prompt cheat sheet. It covers every command you need for important tasks and batch scripting, plus a few delightful surprises if you make it to the end.

Keep a copy of this Windows command line cheat sheet on your desk, in your pocket, or wherever you go. When you’re ready, let’s dive in.

Search our Windows command line cheat sheet to find the right cheat for the term you’re looking for. Simply enter the term in the search bar and you’ll receive the matching cheats available.

What Is the Windows Command Line?

The Windows command line (Windows command prompt) is the command-line interface (CLI) on Microsoft Windows machines, analogous to the Terminal in Unix/Linux. It emulates many command-line abilities in Microsoft’s deprecated text-only operating system MS-DOS (but it’s not MS-DOS).

Methods to open the Windows CLI:

  • On Windows 10 or above, click Start on the bottom left corner, type cmd, and select Command Prompt.
  • On Windows 8.x or earlier, press Ctrl+R to open the Run dialog box, type cmd into it, and press Enter.

Hence, another name for Windows CLI is “cmd.”

Scripts containing Windows commands (batch scripts) have “.bat” as the file extension. All cmd commands are case-insensitive, so arp and ARP are the same. If you need help using any command, add /? to it, e.g., ARP /? will show the manual for ARP:

Table Of Contents

  1. Windows Command Line Cheat Sheet Search
  2. Directory Navigation
  3. File Management
  4. Disk Management
  5. Windows Command Generator
  6. System Information and Networking
  7. Process Management
  8. Batch Scripting
  9. Conclusion
  10. Frequently Asked Questions

Directory Navigation

These commands help you view directories and move directories around.

Command Explanation
c: Change the current drive to the C:\ drive
d: Change the current drive to the D:\ drive
CD c:\path\to\my_folder Change directory to c:\path\to\my_folder
CD .. Navigate to the parent directory of the current working directory
CD .\new_folder Navigate to the folder new_folder located in the current working directory
CD /D d:\videos\ Change the current drive to D:\ and access the folder videos on it.
DIR Display files and folders in the current directory
DIR /A c:\apps\ Display files and folders in the directory c:\apps\
DIR /A:D Display only folders (D: directories)
DIR /A:-D Display only files (D: directories; -: not)
DIR /A:H Display hidden files and folders
DIR /O Display files and folders sorted alphabetically
DIR /O:S Display files and folders sorted by file size from smallest to largest
DIR /O:-S Display files and folders sorted by file size from largest to smallest
DIR /B Display only the names of files and folders in the current working directory
SORT Take input from a source file/pipeline, sort its contents alphabetically (default: A to Z; in reverse: Z to A), and display the output
SORT "C:\music\playlist.m3u" Sort the contents of C:\music\playlist.m3u line by line
DIR /B | SORT /R /O ZtoA.txt List all file and folder names in the current working directory, sort them in reverse alphabetical order, and save the sorted output to a file ZtoA.txt:

MOVE Move a file or files
MOVE c:\f1\text.txt c:\f2 Move a file text.txt from one folder c:\f1 to another folder c:\f2
MD new_folderMAKEDIR new_folder Create a new folder called new_folder in the current directory
RD new_folderRMDIR new_folder Delete the folder called new_folder in the current directory
TREE Show the directory structure of a disk/folder
TREE "C:\Program Files" Show the directory structure of the folder “Program Files” on the disk C:\
TREE C:\ /F Display the names of the files in each folder in the directory structure of the C:\ drive
ATTRIB Display/set the attributes of the files in the current directory
ATTRIB +H +S +R myItem Hide a file/folder myItem
ATTRIB -H -S -R myItem Unhide a file/folder myItem

TREE demonstration

File Management

The following commands are for managing and manipulating files.

Like Unix, cmd supports pipelines: you may pass the output of a command to the next one by sandwiching the pipe character “|” between both.

Command Explanation
COPY text.txt C:\schoolwork Copy the file text.txt to a folder with the path C:\schoolwork
DEL text.txtERASE text.txt Delete the file text.txt
REN text.txt script.batRENAME text.txt script.bat Rename a file text.txt to script.bat
REPLACE .\src\hey.txt .\dest Overwrite; replace a file named hey.txt in a local folder src with another hey.txt in a local folder dest, both files sharing the same name.
Warning: Don’t specify .\dest\hey.txt anywhere here.
XCOPY Copy files and directory trees to another folder.
XCOPY is similar to COPY but with additional switches to specify the source and destination paths in detail.
XCOPY /S folder1 folder2 Copy folders and subfolders of folder1 to folder2
ROBOCOPY Robust copying of files and directories: by default, such copying only occurs if the source and destination differ in time stamps or file sizes.
EXPAND gameData.cab Decompresses the compressed .CAB cabinet file gameData.cab
FC file1.ext file2.ext Compare the contents of two files (file1.ext, file2.ext) and display non-matching lines
COMP file1.ext file2.ext Compare the contents of two files (file1.ext, file2.ext) and display non-matching items
FIND "python" in run.bat Output every line that contains a text string (which you must enclose in quotation marks) «python» in the file run.bat
FIND /C "python" in run.bat Count every line that contains a text string (which you must enclose in quotation marks) «python» in the file run.bat
PRINT resume.txt Print contents of a file resume.txt
OPENFILES /QUERY Query/display open files
OPENFILES /DISCONNECT Disconnect files opened by network users.
TYPE test.txt Displays the contents of the file test.txt
TYPE playlist.m3u | SORT /unique /o C:\work\unique_play.m3u Sort a file playlist.m3u and output only the unique values to a file C:\work\unique_play.m3u
MORE Display contents of one or more files, one screen at a time.
ASSOC Display or change the association between a file extension and a file type
NOTEPAD Open the Notepad application from cmd
NOTEPAD filename.ext Open a file filename.ext in Notepad

Disk Management

It’s easy to handle and automate the following tasks on cmd.

Command Explanation
CHKDSK Check and repair disk problems (local disks only)
CHKDSK /F A: Fix errors on A: drive
CHKDSK /R A: Recover data on A: drive
CHKDSK /X A: Dismount drive A:
CIPHER /E classified Encrypt the folder classified
CIPHER /D secret_recipe.txt Decrypt the file secret_recipe.txt
DEFRAG Disk Defragmentation
CHKNTFS Display/modify disk-checking on startup
COMPACT Display/change the compression of files in NTFS partitions
CONVERT Convert FAT disk volume to NTFS
DISKPART Display and adjust disk partition properties
FORMAT Format the disk
FSUTIL File system management
LABEL d:x Rename disk D:\ to X:\
SUBST p: c:\taxes Assign drive P:\ to the local folder c:\taxes
SUBST p: /D Remove the path represented by P:\
RECOVER d:\data.dat Recover a file data.dat from a bad or defective disk D:\
VOL Display current disk volume label and serial number
POWERCFG Control power settings and configure Hibernate/Standby modes
SFC /SCANNOW Scan and update protected system files

Windows Command Generator

Say goodbye to the hassle of trying to remember the exact syntax for the Windows command line! With our Windows Command Generator, you can simply say what you need Windows to do, and we will generate the command for you.

System Information and Networking

The following commands are helpful in troubleshooting computers and computer networks.

Command Explanation
VER Display the current operating system version
SYSTEMINFO List system configuration
HOSTNAME Show the computer’s hostname on the network
DRIVERQUERY Show all installed device drivers
DATE Display/set system date
TIME Display/set system time
GPRESULT Display Resultant Set of Policy (RSoP) information for a remote user and computer.
GPUPDATE Update group policies
IPCONFIG Display Windows IP network configurations
IPCONFIG /release Release your current local IP address
IPCONFIG /renew Request a new local IP address
IPCONFIG /flushdns Reset the contents of the DNS client resolver cache
PING google.com Send ICMP requests to the target google.com and check host availability
PATHPING Trace route and provide network latency and packet loss for each router and link in the path
NET Provide various network services
NET use M: \\gameServ /user:"ReadyPlayerOne" player1 Assign as disk M:\ the path \\gameServ, logging in as “ReadyPlayerOne” and password “player1
TRACERT Find the IP address of any remote host
NSLOOKUP Find IP addresses on a nameserver
ROUTE Manipulate network routing tables
ROUTE PRINT Displays network route details
ARP -A List IP addresses and corresponding physical addresses (Address Resolution Protocol)
NETSH Configure network interfaces, Windows firewall, routing, and remote access
NETSTAT Display current TCP/IP network connections and protocol statistics
GETMAC Shows all MAC addresses of the network adapters

Process Management

The commands below are Task Manager-like functions. Note that you call variables in arithmetic or logical expressions by enclosing each with two “%” signs (e.g., “%a%”).

Command Explanation
SCHTASKS Create/edit a job on Task Scheduler. Use this to create scheduled tasks in Disk Management.
SET List environment variables
PATH Display/change the list of folders stored in the %PATH% environment variable
SHUTDOWN /R Restart the computer
SHUTDOWN /S /T 60 Shut down the computer 60 seconds from now
TASKLIST List running tasks
TASKLIST /SVC Show services related to each task
TASKLIST /V Display detailed task information
TASKLIST | FIND "1234" Get the name of the executable associated with the process ID (PID) of 1234
TASKKILL End one or more tasks
TASKKILL /IM "msedge.exe" Terminate all Microsoft Edge instances:

TASKKILL /PID 10736 Terminate process with PID of 10736
REGREGEDIT Registry Editor
RUNAS /USER:user2 program1 Execute a program program1 as another user user2
POWERSHELL Open a Powershell instance

Batch Scripting

These commands are for constructing and debugging batch scripts (.bat). To suppress the output of a certain command, add @ in front of it, e.g., @echo off.

Demonstration of CHOICE, PAUSE, and TIMEOUT
Command Explanation
REM comment. . .
:comment. . .
Prefix for the single-line comment “comment. . .”
GOTO end
<comment_block>
:end
Format of multi-line comments represented by <comment_block> enclosed by delimiters end and :end
SET /A c = %a% + %b% Assign the arithmetic expression a+b to the variable c
^ Escape character
some_command > output.txt Redirect output of some_command to a file output.txt
? Wildcard representing one character
* Wildcard representing multiple characters
& Introduce a new command on the same line
TIMEOUT 3600 Tell the command prompt to sleep for 3600 seconds (= 1 hour)
PAUSE Prompt the user to continue
CHOICE Prompt the user to pick an on-screen option
CHOICE /T 15 /C ync /CS /D y /M "Press y=Yes, n=No, c=cancel:" You have 15 seconds to press Y, N, or C keys without capitalization, defaulting to “y” if time runs out without a decision
CLS Clear screen
CMD Restarts Windows command prompt window:

COLOR Set text and background color of cmd:

ECHO ON Display each command executed
ECHO OFF Only display command output
ECHO a string of characters Display a string of characters
HELP Display help
PROMPT topSecret^>$$ Changes the command line prompt to topSecret>$ for the current session
PROMPT Reset the command line prompt to default
START X Start/open a program/document X in a new window
TITLE top Secret Set the title of the current session of Windows command prompt to top Secret
/? Add this to the end of any command word (shown in ALL CAPS in this cheat sheet) to get help on the command, e.g., CD/? = manual for CD (change directory) command
| CLIP Append this to the end of a command to copy the command output to the clipboard
EXIT Exits the command line

Flow Control

Note the condition is a Boolean expression e.g., %a%==5.

Conditional Syntax
If IF (condition) do_something
If-else If (condition) (do_something)
ELSE (do_something_else)
Nested if IF (condition1) IF (condition2) do_something
Infinite loop :marker
do_something
GOTO marker
While loop :marker
IF (condition) (
   do_something
   GOTO :marker
)

Shortcut keys

Any Windows CLI cheat sheet must include methods to speed up your work, such as the following.

Key Effect
Tab Autocomplete
Ctrl+F Find text in console (opens dialog box)
F1, F3, F5, F8 Retype command
F2 Copy the current command leftward of the cursor
F4 Delete the current command rightward of the cursor
F6 Insert end-of-file character
F7 List previous commands from which you choose
F9 Retype a command by typing its line number in the command history

Conclusion

We sincerely hope this Windows cmd commands cheat sheet helps you finish your work quickly and efficiently today, especially if you’re prone to confusing Windows command prompt commands with other terminal scripting languages in the past.

Remember to check out our course offerings on Windows.

Frequently Asked Questions



Can I use the command line for coding?

Like bash, sh, and zsh, the Windows command line is a shell scripting language suited for automating line-by-line execution of programs callable from a command line interface. It’s not suitable as a programming language because it lacks data structures found in general-purpose programming languages such as Python (interpretive) and C++ (compiled).



What are the basic CLI commands?

They’re DIR, CD, CP, DEL, MOVE, REN, MKDIR, RMDIR, CLS, HELP, EXIT, and NOTEPAD. With these commands, a beginner can operate the Windows command prompt and manage most files and folders.



Is learning the command line useful?

Yes. Learning how to use it will allow you to discover your computer’s latent superpowers. You can automate tasks when combined with Run > shell:startup or Task Scheduler (both on Windows). The command line will help you manage and manipulate files and folders more quickly than comparable actions (e.g., drag and drop) on the graphical user interface.



Can CMD run Python?

If the machine has Python installed, then yes. Python isn’t native to Windows. Note that the command to run Python could be one of the following: python, py -2 (for Python 2); python3, py -3 (for Python 3).


  • Cassandra is a writer, artist, musician, and technologist who makes connections across disciplines: cyber security, writing/journalism, art/design, music, mathematics, technology, education, psychology, and more. She’s been a vocal advocate for girls and women in STEM since the 2010s, having written for Huffington Post, International Mathematical Olympiad 2016, and Ada Lovelace Day, and she’s honored to join StationX. You can find Cassandra on LinkedIn and Linktree.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Kb976932 ошибка обновления windows 7
  • Драйвер nvidia geforce 7025 для windows 10 64 bit
  • Acpi int3400 драйвер windows 10 x64
  • Похоже у вас нет разрешения для просмотра этого файла windows 11
  • Using modal windows is not allowed in this mode