c# Run cmd and watch the result is in cmd - c#

I’m suffering with a problem for a month, I want to run the cmd command "sfc / scannow", before that I tried to read the result of this command via StandartOutput, but it’s not working with this command, I had an idea to press the button to call the console with this command and watch the result is in cmd, but I have a problem again, I just have cmd and everything is open, the command is not executed.I need to run the sfc / scannow command and see the process and the result of the check, in any way, but using C # (the project was created on win.forms)Please, help me
Also work with other cmd commands, I read through StandartOutput, but it doesn’t work with this command
string strCmdText;
strCmdText = "sfc/scannow";
Process cmdSFC = Process.Start(new ProcessStartInfo
{
UseShellExecute = true,
WorkingDirectory = #"C:\Windows\System32",
FileName = #"C:\Windows\System32\cmd.exe",
Arguments = "/c " + strCmdText,
});
cmdSFC.WaitForExit();

Set UseShellExecute to false. As described in MSDN:
Setting this property to false enables you to redirect input, output, and error streams.

Related

Execute command line arguments within Coded UI Test Method

Objective
Open command prompt and execute a command autonomously. I use Coded UI for test automation. This task can be completed either programmatically or via UI, it makes no difference.
Problem
I am able to launch a command prompt window, but I am unable to execute a command, or pass any input to it for that matter. I have tried both examples below to execute a basic command in the command prompt, but with no success.
First attempt:
Process.Start(new ProcessStartInfo
{
FileName = "C:\\Windows\\System32\\cmd.exe",
UseShellExecute = false,
Arguments = "cd C:\\"
});
Second attempt:
Process.Start(new ProcessStartInfo
{
FileName = "C:\\Windows\\System32\\cmd.exe",
UseShellExecute = false,
});
Keyboard.SendKeys("cd C:\\{Enter}");
Question
Is there an effective way to execute commands in the command line using Coded UI? Any suggestions are appreciated.

How to use CSSLint?

I found some command line arguments to run generate the CSSLint report in xml format. It is working fine while running through command prompt.
Arguments:
csslint --format=csslint-xml "{SourceDir}\bootstrap.css" > "C:\temp\csslint.xml"
I want to execute it through C# application. I tried the below code.
Process process = new Process()
{
StartInfo =
{
FileName = "cmd.exe",
Arguments = "csslint --format=csslint-xml " + #"""{SourceDir}\bootstrap.css""" + #" > ""C:\Temp\CssLint.xml""",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
}
};
process.Start();
process.WaitForExit();
But it is not working. Can i have a solution or idea for this issue?
Also is there any way to generate the CSSLint report for the specified directory? I want to give the directory path instead of file name.
You need to add /Kor /C to cmd to execute a process passed as a parameter, thus:
Arguments = "/C csslint --format=csslint-xml " + #"""{SourceDir}\bootstrap.css""" + #" > ""C:\Temp\CssLint.xml""",
From the documentation:
Options
/C Run Command and then terminate
/K Run Command and then return to the CMD prompt.
This is useful for testing, to examine variables
One caveat... the piping (the > "C:\temp\csslint.xml" part of your command line) is not an argument, it's a redirection.
If you are redirecting your stdout (the RedirectStandardOutput = true) from your app, you can capture it directly from C#, no need to pipe it to a file like you are trying to do: you'd need to handle the Process.OutputDataReceived event between your Start and WaitForExit calls, or read from the Process.StandardOutput stream).
As for your second question, the csslint CLI allows passing in a directory instead of a file

c# open cmd.exe process and Execute multiple commands

I would like to be able to open cmd and execute two commands from the window. First I would like to navigate to a particular directory where I can then run the second command from. Running a single command is pretty easy as this is all I have to do:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Cisco Systems\VPN Client\";
Process process = new Process();
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/c cd " + path );
process.StartInfo = processInfo;
process.Start();
However am not sure of the way to add the second argument so it runs after cmd runs the first command. Some research led me to this code snippet. Am unsure if this works since my aim is to start cisco vpn client from cmd and this seems not to start it. Here is the code:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Cisco Systems\VPN Client\";
Process process = new Process();
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/c cd " + path + "-t vpnclient connect user validuser pwd validpassword nocertpwd validconnectionentry ");
process.StartInfo = processInfo;
process.Start();
I once started the vpn client from cmd with the credentials just to make sure they were valid and it worked but I cant pull it off via C# programmatically.
Regards.
There three things you can do to achieve what you want. The easiest is to set the working directory of the process through ProcessStartInfo. This way you will only have to execute the command to start the VPN client.
The second option is redirecting the input and output of the process. (Also done through the ProcessStartInfo) This is something you want to do if you need to send more input to the process, or when you want to retrieve the output of the process you just started.
The third option is to combine the two commands with the & symbol. Using the & symbol makes cmd.exe execute the two commands sequentially (See here for an overview of the available symbols). Using this option will result in a command like this: /c cd path & vpnclient.
However because you just want to change the working directory of the process using the first option makes your code more readable. Because people reading your code do not need to know the & symbol in bash to understand what your code does. Changing the working directoy is done with the WorkingDirectory (MSDN) property of ProcessStartInfo (MSDN). See the following code:
var processInfo = new ProcessStartInfo("cmd.exe", #"/c vpnclient connect user validuser pwd validpassword nocertpwd validconnectionentry ");
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = path;
You can use & to execute next command or && to execute following command only if the previous one succeeded.
Examples:
dir /b & cls
and
taskkill /f /im explorer.exe && start explorer

How to execute cmd statement for clearing saved credentials of network from the windows cache using c#?

I need to remove saved credentials of network shares from the windows cache programmatically.I searched for it but couldn't find a solution. But I solved this issue by executing the following statement in command prompt.
net use \\someloaction /del
Now i need to execute the cmd statement using asp.net c#.
I tried the following code. But its not working.
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = new Process { StartInfo = startInfo };
process.Start();
process.StandardInput.WriteLine("net use \somelocation /del");
process.StandardInput.WriteLine("exit");
process.WaitForExit();
You should use the Arguments property of ProcessStartInfo class.
The /C flag serves to pass the arguments to the Shell Command Processor for execution otherwise it will close immediately.
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = #"/C net use \\somelocation /del",
UseShellExecute = false,
CreateNoWindow = true
};
However, the NET USE .... /D command doesn't remove the CREDENTIALS stored for your user to access the network share. If you need to remove the credentials, forcing the user to reinsert them the next time that he/she wants to use the shared resource you need to work with the Credential Manager.
The problem is that this library has no official managed implementation (AFAIK). So you need to use a plugin library that you can download from here or use the NuGet install with the command Install-Package CredentialManagement
So, after removing the sharing with the previous NET USE command, you could write in your code something like this
Credential cm = new Credential(#"\\server\share","", #"server");
cm.Delete();
You could find another question about this at this link
(Tried this library and I am able to clear the credentials to access a shared network on my lan using a command prompt. I hope the same happens on your side)

Writing and executing multiple lines sequentially in an elevated command prompt using c#

Am a Newbie in C# and I have 3 commands(command2, command3 and command4) I need to execute in the elevated command prompt and I will also like to view the execution process as it happens. Currently, the problem is that the code below just opens the elevated command prompt and without executing the commands. I also seek better interpretations of the lines if wrong.
My code and Interpretation/Understanding of each line based on reviews of similar cases: ConsoleApp1
class Program
{
static void Main(string[] args)
{
string command2 = #"netsh wlan";
string command3 = #" set hostednetwork mode=true ssid=egghead key=beanhead keyusage=persistent";
string command4 = #" start hostednetwork";
string maincomm = command2.Replace(#"\", #"\\") + " " + command3.Replace(#"\", #"\\") ; //I merged commands 2 and 3
ProcessStartInfo newstartInfo = new ProcessStartInfo();
newstartInfo.FileName = "cmd"; //Intend to open cmd. without this the newProcess hits an error saying - Cannot run process without a filename.
newstartInfo.Verb = "runas"; //Opens cmd in elevated mode
newstartInfo.Arguments = maincomm; //I intend to pass in the merged commands.
newstartInfo.UseShellExecute = true; //
newstartInfo.CreateNoWindow = true; // I intend to see the cmd window
Process newProcess = new Process(); //
newProcess.StartInfo = newstartInfo; //Assigns my newstartInfo to the process object that will execute
newProcess.Start(); // Begin process and Execute newstartInfo
newProcess.StartInfo.Arguments = command4; //I intend to overwrite the initial command argument hereby passing the another command to execute.
newProcess.WaitForExit(); //
}
}
This is what I did to overcome the challenge and It gave me exactly what I wanted. I modified my code to use the System.IO to write directly to the elevated command prompt.
ProcessStartInfo newstartInfo = new ProcessStartInfo();
newstartInfo.FileName = "cmd";
newstartInfo.Verb = "runas";
newstartInfo.RedirectStandardInput = true;
newstartInfo.UseShellExecute = false; //The Process object must have the UseShellExecute property set to false in order to redirect IO streams.
Process newProcess = new Process();
newProcess.StartInfo = newstartInfo;
newProcess.Start();
StreamWriter write = newProcess.StandardInput ; //Using the Streamwriter to write to the elevated command prompt.
write.WriteLine(maincomm); //First command executes in elevated command prompt
write.WriteLine(command4); //Second command executes and Everything works fine
newProcess.WaitForExit();
Referrence: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardinput(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.110).aspx
I think an understanding of some properties of the ProcessStartInfo might clear things.
The verb - Gets or sets the verb to use when opening the application or document specified by the FileName property.,
+The UseShellExecute - Gets or sets a value indicating whether to use the operating system shell to start the process.
+The FileName - Gets or sets the application or document to start MSDN Docs
When you use the operating system shell to start processes, you can start any document (which is any registered file type associated with an executable that has a default open action) and perform operations on the file, such as printing, by using the Process object. When UseShellExecute is false, you can start only executables by using the Process object Documentation from MSDN.
In my case, cmd is an executable. the verb property is some thing that answers the question "How should my I run my FileName(for executables e.g cmd or any application)?" for which I answered - "runas" i.e run as administrator. When the FileName is a document (e.g `someFile.txt), the verb answers the question "What should I do with the file for which answer(verb) could be -"Edit","print" etc. also?"
use true if the shell should be used when starting the process; false if the process should be created directly from the executable file. The default is true MSDN Docs - UserShellInfo.
Another thing worth noting is knowing what you are trying to achieve. In my case, I want to be able to run commands via an executable(cmd prompt) with the same process - i.e starting the cmd as a process I can keep track of.

Categories