c# – Run Command Prompt Commands – Stack Overflow

Cmd command not running in console

The following code will perform any console command you want and output the console text in your current window, everything after while(true) is just as example:

        ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe");
        cmd.RedirectStandardInput = true;
        cmd.UseShellExecute = false;
        cmd.CreateNoWindow = false;
        cmd.WindowStyle = ProcessWindowStyle.Normal;
        Process console = Process.Start(cmd);

        while(true)
            console.StandardInput.WriteLine("pause");

If you don’t want any console output then set CreateNoWindow to true. Also this code works inside a console application using System.Diagnostics

Good luck!

Errorlevels

If the command is successfully started ERRORLEVEL =unchanged, typically this will be but if a previous command set an errorlevel, that will be preserved (this is a bug).
If the command fails to start then ERRORLEVEL = 9059
START /WAIT batch_file – will return the ERRORLEVEL specified by EXIT

Examples

Run a minimised Login script: START “My Login Script” /Min Login.cmd

Start a program and wait for it to complete before continuing: START “” /wait autocad.exe

Open a file with a particular program:START “” “C:Program FilesMicrosoft OfficeWinword.exe” “D:Docsdemo.txt”

Open Windows Explorer and list the files in the current folder (.) :C:anyolddirectory> START .

Multiprocessor systems

Processor affinity is assigned as a hex number but calculated from the binary positions (similar to NODRIVES)

Hex Binary        Processors
 1 00000001 Proc 1 
 3 00000011 Proc 1 2
 7 00000111 Proc 1 2 3
 C 00001100 Proc 3 4 etc

Specifying /NODE allows processes to be created in a way that leverages memory locality on NUMA systems. For example, two processes that communicate with each other heavily through shared memory can be created to share the same preferred NUMA node in order to minimize memory latencies. They allocate memory from the same NUMA node when possible, and they are free to run on processors outside the specified node.

start /NODE 1 app1.exe
start /NODE 1 app2.exe

These two processes can be further constrained to run on specific processors within the same NUMA node.

In the following example, app1 runs on the low-order two processors of the node, while app2 runs on the next two processors of the node. This example assumes the specified node has at least four logical processors. Note that the node number can be changed to any valid node number for that computer without having to change the affinity mask.

start /NODE 1 /AFFINITY 0x3 app1.exe
start /NODE 1 /AFFINITY 0xc app2.exe

Nning can’t start service and n service xxx start jam. · issue #5469 · saltstack/salt

[root@gs-amazon init.d]# /sbin/service manticore start
Starting manticore[INFO] Extracting properties
Jun 13, 2021 3:36:58 PM com.google.code.morphia.logging.MorphiaLoggerFactory chooseLoggerFactory
INFO: LoggerImplFactory set to com.google.code.morphia.logging.jdk.JDKLoggerFactory
[INFO] Server started
OK
[root@gs-amazon init.d]# echo $?
0

:/>  Стандартные игры для Windows 10 — Как вернуть любимые приложения?

and :
[root@gs-amazon init.d]# /sbin/service manticore stop
Stopping manticore: process 2790
OK
[root@gs-amazon init.d]# echo $?

and:
[root@gs-amazon init.d]# salt-call service.start manticore -l debug
[DEBUG ] Reading configuration from /etc/salt/minion
[DEBUG ] Guessing ID. The id can be explicitly in set /etc/salt/minion
[INFO ] Found minion id from getfqdn(): gs-amazon.xxxx.xxx
[INFO ] Configuration file path: /etc/salt/minion
[DEBUG ] Reading configuration from /etc/salt/minion
[DEBUG ] loading grain in [‘/var/cache/salt/minion/extmods/grains’, ‘/usr/local/lib/python2.7/site-packages/salt-0.15.3-py2.7.egg/salt/grains’][DEBUG ] Skipping /var/cache/salt/minion/extmods/grains, it is not a directory
[DEBUG ] Loaded minion key: /etc/salt/pki/minion/minion.pem
[DEBUG ] Decrypting the current master AES key
[DEBUG ] Loaded minion key: /etc/salt/pki/minion/minion.pem
[DEBUG ] Loaded minion key: /etc/salt/pki/minion/minion.pem
[DEBUG ] loading module in [‘/var/cache/salt/minion/extmods/modules’, ‘/usr/local/lib/python2.7/site-packages/salt-0.15.3-py2.7.egg/salt/modules’][DEBUG ] Loaded localemod as virtual locale
[DEBUG ] Loaded groupadd as virtual group
[DEBUG ] Loaded rh_service as virtual service
[DEBUG ] Loaded parted as virtual partition
[DEBUG ] Loaded linux_sysctl as virtual sysctl
[DEBUG ] Loaded mdadm as virtual raid
[DEBUG ] Loaded linux_acl as virtual acl
[DEBUG ] Loaded sysmod as virtual sys
[DEBUG ] Loaded rpm as virtual lowpkg
[DEBUG ] Loaded useradd as virtual user
[DEBUG ] Loaded grub_legacy as virtual grub
[DEBUG ] Loaded rh_ip as virtual ip
[DEBUG ] Loaded cmdmod as virtual cmd
[DEBUG ] Loaded djangomod as virtual django
[DEBUG ] Loaded linux_lvm as virtual lvm
[DEBUG ] loading returner in [‘/var/cache/salt/minion/extmods/returners’, ‘/usr/local/lib/python2.7/site-packages/salt-0.15.3-py2.7.egg/salt/returners’][DEBUG ] Skipping /var/cache/salt/minion/extmods/returners, it is not a directory
[DEBUG ] Loaded syslog_return as virtual syslog
[DEBUG ] Loaded carbon_return as virtual carbon
[DEBUG ] loading states in [‘/var/cache/salt/minion/extmods/states’, ‘/usr/local/lib/python2.7/site-packages/salt-0.15.3-py2.7.egg/salt/states’][DEBUG ] Skipping /var/cache/salt/minion/extmods/states, it is not a directory
[DEBUG ] Loaded mdadm as virtual raid
[DEBUG ] loading render in [‘/var/cache/salt/minion/extmods/renderers’, ‘/usr/local/lib/python2.7/site-packages/salt-0.15.3-py2.7.egg/salt/renderers’][DEBUG ] Skipping /var/cache/salt/minion/extmods/renderers, it is not a directory
[INFO ] Executing command ‘/sbin/runlevel’ in directory ‘/home/frima_xxxx’
[DEBUG ] output: N 3
[INFO ] Executing command ‘/sbin/chkconfig –list’ in directory ‘/home/frima_xxx’
[DEBUG ] output: auditd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
blk-availability 0:off 1:on 2:on 3:on 4:on 5:on 6:off
crond 0:off 1:off 2:on 3:on 4:on 5:on 6:off
htcacheclean 0:off 1:off 2:off 3:off 4:off 5:off 6:off
httpd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
ip6tables 0:off 1:off 2:on 3:on 4:on 5:on 6:off
iptables 0:off 1:off 2:on 3:on 4:on 5:on 6:off
iscsi 0:off 1:off 2:off 3:on 4:on 5:on 6:off
iscsid 0:off 1:off 2:off 3:on 4:on 5:on 6:off
jexec 0:on 1:on 2:on 3:on 4:on 5:on 6:on
lvm2-monitor 0:off 1:on 2:on 3:on 4:on 5:on 6:off
manticore 0:off 1:off 2:on 3:on 4:on 5:on 6:off
mdmonitor 0:off 1:off 2:on 3:on 4:on 5:on 6:off
multipathd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
netconsole 0:off 1:off 2:off 3:off 4:off 5:off 6:off
netfs 0:off 1:off 2:off 3:on 4:on 5:on 6:off
network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
postfix 0:off 1:off 2:on 3:on 4:on 5:on 6:off
rdisc 0:off 1:off 2:off 3:off 4:off 5:off 6:off
restorecond 0:off 1:off 2:off 3:off 4:off 5:off 6:off
rsyslog 0:off 1:off 2:on 3:on 4:on 5:on 6:off
salt-minion 0:off 1:off 2:on 3:on 4:on 5:on 6:off
saslauthd 0:off 1:off 2:off 3:off 4:off 5:off 6:off
sshd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
svnserve 0:off 1:off 2:off 3:off 4:off 5:off 6:off
udev-post 0:off 1:on 2:on 3:on 4:on 5:on 6:off
[INFO ] Executing command ‘/sbin/service manticore start’ in directory ‘/home/frima_xxxx’

:/>  Не отображаются все программы в меню пуск windows 10

Run a program

To start a new program (not a batch script), you don’t have to use CALL or START, just enter the path/file to be executed, either on the command line or within a batch script. This will behave as follows:

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.

:/>  AIMP

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.

Running executable (.exe) files

When a file that contains a .exe header, is invoked from a CMD prompt or batch file (with or without START), it will be opened as an executable file. The filename extension does not have to be .EXE. The file header of executable files start with the ‘magic sequence’ of ASCII characters ‘MZ’ (0x4D, 0x5A) The ‘MZ’ being the initials of Mark Zibowski, a Microsoft employee at the time the file format was designed.

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

Adblock
detector