I am creating a C# app that changes Windows Server edition from Standard Evaluation to Standard. I am trying to get a output of the CMD command, but when the DISM command is completed, it asks you if you want to restart the computer and you need to enter "y" or "n". I tried it doing by passing "echo n | " before the command and by using process.StandardInput.Write, but none of this works. The function works perfectly with other commands that doesn´t require user input. Do you have any idea what am I doing wrong? Thanks
public static string get_cmd_output(string cmd)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C echo n | " + cmd;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string q = "";
while (!process.HasExited)
q += process.StandardOutput.ReadToEnd();
return q;
}
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula");
In the docs for DISM, one of the global parameters you can pass is /NoRestart:
/NoRestart
Suppresses reboot. If a reboot is not required, this command does
nothing. This option will keep the application from prompting for a
restart (or keep it from restarting automatically if the /Quiet option
is used).
So it should work if you do this:
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula /NoRestart");
Related
I am using PsExec to remotely fire a program. I can fire the actual program (not displayed here) or cmd.exe remotely with no problems whatsoever from the command line. When I try to fire it from ASP and C#, it will not trigger the command prompt, even though I am using the same exact string. Here is the string I am using that works every time, and the code that doesn't. Help please!
Working String: C:\psexec \\10.0.0.25 -u Administrator -p password -d -i cmd.exe
Non-working code:
ProcessStartInfo psi = new ProcessStartInfo(#"C:\PsExec.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
Arguments = #"\\10.0.0.25 -u Administrator -p password -d -i cmd.exe"
};
process.StartInfo = psi;
var success = process.Start();
One option, assuming you have control over the machine, is to setup the psexec command as a Task Scheduler job, then execute the task scheduler job from your ASP app. You can configure the task scheduler to run as an administrator, and when you fire off the job it will run under that credentials. You won't get any output that way though, so if that's an issue there may not be a good choice.
See How to run existing windows 7 task using command prompt for an example of running the task..
It's been a while since I was a system administrator, but if I recall correctly psexec has to be run from an administrative command prompt. Maybe the account your app is running under doesn't have rights to reach across the network and do stuff to a remote machine?
Put this in your Page_Load temporarily:
Response.Write(Environment.UserName);
and run it again, it should show you the name you're looking for at the top of your app.
Well, I am right now doing some automation and have figured out a few things. Please see below code maybe it will help you out
public static void PSExec_Method()
{
try
{
string userName = #"ABC";
string password = "ABC";
string remoteMachine = "ABC";
//How to restart AppPool
//string operation = "stop";
//string apppoolname = "APPPOOL";
//string command = #"%SYSTEMROOT%\System32\inetsrv\appcmd " + operation + " apppool /apppool.name:\"" + apppoolname + "\"";
string command = #"powershell -noninteractive Get-Content C:\tmp\tmp.csv -Head 5";
//string command = #"ipconfig";
string PSPath = #"C:\PSTools\PsExec.exe";
string fullcommand = PSPath + " -u " + userName + " -p " + password + " \\\\" + remoteMachine + " -h cmd.exe /c " + command;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = fullcommand;
process.Start();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.WriteLine(process.StandardError.ReadToEnd());
process.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
My windows forms app triggers an event:
using System.Diagnostics;
string strCmdText = "'/C ping server1.example.com > C:\\Users\\myusername\\Desktop\\1\\a.txt";
Process.Start("cmd.exe", strCmdText);
When executing, cmd.exe is getting spawned, runs for a while, the output is not displayed, but it is present in the redirected 1.txt file.
However, I need to run query command:
using System.Diagnostics;
string strCmdText = "'/C query user /server:server1.example.com > C:\\Users\\myusername\\Desktop\\1\\a.txt";
Process.Start("cmd.exe", strCmdText);
When executing, it spawns a cmd.exe but just for 1 second, then it dissapears, and the output is not present in the 1.txt file.
Is there any way to see what the query command does before it disappears, like keep it open when executing? Maybe is something interesting in there.
Or, am I doing something wrong? Maybe I need to run the command otherwise?
This way:
string outputProcess = "";
string errorProcess = "";
using (Process process = new Process())
{
process.StartInfo.FileName = yourPath;
process.StartInfo.Arguments = yourArguments;
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
outputProcess = process.StandardOutput.ReadToEnd();
errorProcess = process.StandardError.ReadToEnd();
process.WaitForExit();
}
if you really want to run the code as yours. just replace the "CMD" to "CMD /k"
I am currently trying to make an application that uses the command net share from the CMD. However, when I press on the button that runs the code, it gives me the following error:
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll.
Here's the code I'm using:
Process cmd = new Process();
cmd.StartInfo.FileName = "net share";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
txt_Logs.Text = cmd.StandardOutput.ReadToEnd();
But when you put ipconfig into the FileName part and /all into the Arguments part, it works perfectly.
The issue is with the StartInfo.File, "net share" is not a valid filename.
Try this
Process cmd = new Process()'
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
If the path contain spaces, you will need to quote it.
Process cmd = new Process();
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share";
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
net is a exe in sys32.. share is an argument.. add it to your aguments..
It is because net share requires Administrative privilege to run this command.
When you try to run only Net Share it will perfectly and it doesn't require any special privilege. But when you try run the command with parameters in the command prompt it will give error stating
System error 5 has occurred.
Access is denied.
So you need to run as administrator
The possible solution might be that you could run the Visual Studio as administrator
To run the command with administrator privilege whereas if the OS is Vista or higher you can do it like below
if (System.Environment.OSVersion.Version.Major >= 6)
{
p.StartInfo.Verb = "runas";
}
As mentioned by #Mohit, this is a problem of admin rights. You can run process as administrator from C# by adding following:
cmd.StartInfo.Verb = "runas";
"net" it's a programm and "share" argument. Try this:
cmd.StartInfo.FileName = "net";
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;
I'd like to execute a batch file without showing terminal window
and I need to get the standard output contents.
Here is the batch file:
timeout /T 5
exit 0
Below is my partial C# code:
static void Main(string[] args)
{
bool ShowTerminal = true;
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
string ExecContent = "\"" + args[0] + "\"";
proc.StartInfo.Arguments = "/c " + ExecContent;
proc.StartInfo.UseShellExecute = ShowTerminal;
proc.StartInfo.RedirectStandardError = !ShowTerminal;
proc.StartInfo.RedirectStandardInput = !ShowTerminal;
proc.StartInfo.RedirectStandardOutput = !ShowTerminal;
proc.Start();
proc.WaitForExit();
}
I found that variable ShowTerminal set true, then everything is going well
except I can not get standard output contents
But if variable ShowTerminal set false, timeout command will be skipped
Is there any solution for this problem? Thanks!
If you specify "redirect" options you should also provide their redirection streams (STDIN, STDOUT) and ensure they are being emptied/read/processed as CMD would expect.
Chances are good that 'timeout' is failing to detect any STDIN/STDOUT and therefore performs a noop.
I need to run a legacy app that is run from a cmd window using the Process class.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe –r " + Parameters.FullPath;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch (Exception e)
{
string sMsg = "Error copying the files to " + Parameters.FullPath + ".";
HandleErrorMsg(e, sMsg);
return;
}
The process My2Com.exe should run in the background, however, I consistantly get the message that a file, used when run from the cmd line with different flags, is missing. If I run the command as indicated in a cmd window, C:\MySys\My2Com.exe –r FullyQualPath, it works as expected. I have tried several different ways to set up the Process class without success.
Any suggestions would be appreciated.
Thank you.
Try this one -
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe –r\" " + Parameters.FullPath;
will this work if you do the following
startInfo.Arguments = #"/C "C:\MySys\My2Com.exe /r" " + Parameters.FullPath +"\"";
keep in mind that if there are spaces in the filepath you need to wrap around """ for example if the filepath were like this #"""C:\Wolf Lair\WorkDeskTemp\"
notice the # and the """
you need to append the ending quotes to the string +"\""; after Parameters.FullPath;
You know why is it not working because
You haven't completed quotes
Try this:-
startInfo.Arguments = "/C \"C:\\MySys\\My2Com.exe\" –r \"" + Parameters.FullPath+"\"";
startInfo.Arguments = #"/C ""C:\MySys\My2Com.exe –r """ + Parameters.FullPath + "\"";
Also, see Sending commands to cmd prompt in C#. I'd recommended using some of the code from my answer there so that you can intercept the standard output and standard error to see what you're getting.