How to Open Command Prompt (Windows 10, 8, 7, etc.)

Запуск cmd из контекстного меню Пуска

Нажмите на Пуск правой кнопкой мыши или нажмите комбинацию Win X, причем клавишами быстрее, я гарантирую это;) Появится контекстное меню, в котором выбираем пункт Командная строка (администратор). Готово!

Через диспетчер задач

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

Вводим cmd и ставим галочку чуть ниже Создать задачу с правами администратора. И затем ОК.

Через диспетчер задач (хитрый способ)

Третий способ очень похож на второй, но чуть более быстрый и не такой известный.

Начало такое же, то есть, в Диспетчере задач выбираем Файл -> Запустить новую задачу, но когда кликаете мышкой по этому пункту — удерживайте клавишу Ctrl. В этом случае сразу запускается cmd в режиме администратора, без лишних разговоров.

Запуск cmd из поиска Windows 10

Нажмите комбинацию Win S либо прицельтесь левой кнопкой мышки в значок лупы справа от кнопки Пуск. В поле поиска можно ввести либо на английском ‘cmd‘ либо на русском введите первые 5-6 букв от названия ‘Командная строка‘. Затем правой кнопкой мыши нажимаем на результате поиска, выбираем Запустить от имени администратора.

Запускаем cmd из меню Все приложения

Открываем Пуск, кликаем на Все приложения и отыскиваем пункт Служебные — Windows. Обычно он прячется в самом низу, так что промотайте колесиком мышки до самого конца.

Итак, нашли группу Служебные, раскрыли список программ внутри и обнаружили Командную строку. Правой кнопкой по ней кликаем, затем Дополнительно, потом Запуск от имени администратора.

Запуск из системного каталога WindowsSystem32

Можно запустить командную строку прямо из ее родной папки system32. Для этого заходим в Проводник / Мой компьютер, находим диск C, ищем папку Windows, идём туда, находим папку System32,

углубляемся все дальше и дальше в кроличью нору

заходим в неё. В папке System32 ищем файл

cmd.exe

. Выделяем его. И тут появляется два варианта.

Самый быстрый и простой: правой кнопкой мышки кликаем на cmd.exe и выбираем уже знакомый нам Запуск от имени администратора.

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

Запуск cmd из любой папки Проводника

Этот вариант открытия командной строки доступен из любой папки Проводника Windows 10. Заходите в нужное вам место, заходите в меню Файл -> Открыть командную строку -> Открыть командную строку как администратор.

Создаем админский ярлык для cmd.exe

Для быстрого доступа к админской командной строке сделаем следующее.

На рабочем столе на свободном месте кликаем правой кнопкой, выбираем Создать -> Ярлык.

Вводим cmd или cmd.exe, оба вариант будут работать. Далее.

Elevated command prompts and old windows versions

In versions of Windows released before Windows XP, like Windows 98 and Windows 95, Command Prompt doesn’t exist. However, the older and very similar MS-DOS Prompt does. This program is located in the Start menu and can be opened with the command run command.

:/>  Пинг из другой подсети

How do i execute an executable file through cmd

If the executable for your program is “My Program” in directory “c:My Directory” then to execute that program within a batch file, use

"C:My DirectoryMy Program"

or

"C:My DirectoryMy Program.exe"

or

START "" "C:My DirectoryMy Program"

or equally

START "" "C:My DirectoryMy Program.exe"

Use the START version if you want your batch to continue to the next line once it has started the program.

The "" in the start version is the window title. You can place any window title you want within those quotes, but should not omit that "titling" pair.

How i can execute cmd command in c# console application?

It’s very simple to make a mysqldump in cmd on windows, simply:

Open cmd and put type mysqldump uroot ppassword database > c:/data.sql

This results in an SQL dump file for the desired database.

I’m writing a console application so I may run this command:

-uroot -ppass databse  > locationdata.sql

I tried the following code to no avail:

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c "   cmd); 

How might I start a cmd process and send my command successfully?

How to execute a cmd command using qprocess?

QProcess::startDetached will take the first parameter as the command to execute and the following parameters, delimited by a space, will be interpreted as separate arguments to the command.

Therefore, in this case: –

QProcess::startDetached("cmd /c net stop "MyService"");

The function sees cmd as the command and passes /c, net, stop and “MyService” as arguments to cmd. However, other than /c, the others are parsed separately and are not valid arguments.

What you need to do is use quotes around the “net stop “MyService” to pass it as a single argument, so that would give you: –

QProcess::startDetached("cmd /c "net stop "MyService""");

Alternatively, using the string list you could use: –

QProcess::startDetached("cmd", QStringList() << "/c" << "net stop "MyService"");

How to open an elevated cmd using command line for windows?

Similar to some of the other solutions above, I created an elevate batch file which runs an elevated PowerShell window, bypassing the execution policy to enable running everything from simple commands to batch files to complex PowerShell scripts. I recommend sticking it in your C:WindowsSystem32 folder for ease of use.

The original elevate command executes its task, captures the output, closes the spawned PowerShell window and then returns, writing out the captured output to the original window.

:/>  Скачать GeForce Experience | NVIDIA

I created two variants, elevatep and elevatex, which respectively pause and keep the PowerShell window open for more work.

https://github.com/jt-github/elevate

And in case my link ever dies, here’s the code for the original elevate batch file:

@Echo Off
REM Executes a command in an elevated PowerShell window and captures/displays output
REM Note that any file paths must be fully qualified!

REM Example: elevate myAdminCommand -myArg1 -myArg2 someValue

if "%1"=="" (
    REM If no command is passed, simply open an elevated PowerShell window.
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -Verb RunAs}"
) ELSE (
    REM Copy command arguments (passed as a parameter) into a ps1 file
    REM Start PowerShell with Elevated access (prompting UAC confirmation)
    REM     and run the ps1 file
    REM     then close elevated window when finished
    REM Output captured results

    IF EXIST %temp%trans.txt del %temp%trans.txt
    Echo %* ^> %temp%trans.txt *^>^&1 > %temp%tmp.ps1
    Echo $error[0] ^| Add-Content %temp%trans.txt -Encoding Default >> %temp%tmp.ps1
    PowerShell -Command "& {Start-Process PowerShell.exe -Wait -ArgumentList '-ExecutionPolicy Bypass -File ""%temp%tmp.ps1""' -Verb RunAs}"
    Type %temp%trans.txt
)

Open command prompt in windows 10

  1. Select the Start button.

  2. Type cmd.

  3. Select Command Prompt from the list.

Open command prompt through the start menu

Another way to open Command Prompt in Windows 10 is to look in its Start menu folder:

  1. Select the Start button.

  2. Select the Windows System folder from the list.

  3. Choose Command Prompt from the folder group.

Other ways to open command prompt

Command Prompt in Windows XP through Windows 10 can also be opened with a command. This is especially helpful if you like using the Run dialog box or if Windows Explorer has crashed and the Start menu is inaccessible (and thus the directions above don’t work).

To do this, enter cmd into the command-line interface. This can be in the Run dialog box (WIN R) or Task Manager’sFile > Run new task menu.

Run command prompt commands

This may be a bit of a read so im sorry in advance. And this is my tried and tested way of doing this, there may be a simpler way but this is from me throwing code at a wall and seeing what stuck

If it can be done with a batch file then the maybe over complicated work around is have c# write a .bat file and run it. If you want user input you could place the input into a variable and have c# write it into the file. it will take trial and error with this way because its like controlling a puppet with another puppet.

here is an example, In this case the function is for a push button in windows forum app that clears the print queue.

using System.IO;
using System;

   public static void ClearPrintQueue()
    {

        //this is the path the document or in our case batch file will be placed
        string docPath =
         Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        //this is the path process.start usues
        string path1 = docPath   "\Test.bat";

        // these are the batch commands
        // remember its "", the comma separates the lines
        string[] lines =
        {
            "@echo off",
            "net stop spooler",
            "del %systemroot%\System32\spool\Printers\* /Q",
            "net start spooler",
            //this deletes the file
            "del "%~f0"" //do not put a comma on the last line
        };

        //this writes the string to the file
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
        {
            //This writes the file line by line
            foreach (string line in lines)
                outputFile.WriteLine(line);
        }
        System.Diagnostics.Process.Start(path1);

    }

IF you want user input then you could try something like this.

:/>  Old Calculator for Windows 10 - классический калькулятор

This is for setting the computer IP as static but asking the user what the IP, gateway, and dns server is.

you will need this for it to work

public static void SetIPStatic()
    {
//These open pop up boxes which ask for user input
        string STATIC = Microsoft.VisualBasic.Interaction.InputBox("Whats the static IP?", "", "", 100, 100);
        string SUBNET = Microsoft.VisualBasic.Interaction.InputBox("Whats the Subnet?(Press enter for default)", "255.255.255.0", "", 100, 100);
        string DEFAULTGATEWAY = Microsoft.VisualBasic.Interaction.InputBox("Whats the Default gateway?", "", "", 100, 100);
        string DNS = Microsoft.VisualBasic.Interaction.InputBox("Whats the DNS server IP?(Input required, 8.8.4.4 has already been set as secondary)", "", "", 100, 100);



        //this is the path the document or in our case batch file will be placed
        string docPath =
         Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        //this is the path process.start usues
        string path1 = docPath   "\Test.bat";

        // these are the batch commands
        // remember its "", the comma separates the lines
        string[] lines =
        {
            "SETLOCAL EnableDelayedExpansion",
            "SET adapterName=",
            "FOR /F "tokens=* delims=:" %%a IN ('IPCONFIG ^| FIND /I "ETHERNET ADAPTER"') DO (",
            "SET adapterName=%%a",
            "REM Removes "Ethernet adapter" from the front of the adapter name",
            "SET adapterName=!adapterName:~17!",
            "REM Removes the colon from the end of the adapter name",
            "SET adapterName=!adapterName:~0,-1!",
//the variables that were set before are used here
            "netsh interface ipv4 set address name="!adapterName!" static "   STATIC   " "   STATIC   " "   DEFAULTGATEWAY,
            "netsh interface ipv4 set dns name="!adapterName!" static "   DNS   " primary",
            "netsh interface ipv4 add dns name="!adapterName!" 8.8.4.4 index=2",
            ")",
            "ipconfig /flushdns",
            "ipconfig /registerdns",
            ":EOF",
            "DEL "%~f0"",
            ""
        };

        //this writes the string to the file
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
        {
            //This writes the file line by line
            foreach (string line in lines)
                outputFile.WriteLine(line);
        }
        System.Diagnostics.Process.Start(path1);

    }

Like I said. It may be a little overcomplicated but it never fails unless I write the batch commands wrong.

Оставьте комментарий