To run cmd as administrator along with command? - c#

Here is my code:
try
{
ProcessStartInfo procStartInfo = new ProcessStartInfo(
"cmd.exe",
"/c " + command);
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
procStartInfo.Verb = "runas";
procStartInfo.Arguments = "/env /user:" + "Administrator" + " cmd" + command;
///command contains the command to be executed in cmd
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I want to keep
procStartInfo.UseShellExecute = true
procStartInfo.RedirectStandardInput = false;
Is it possible to execute the command without using process.standardinput?
I try to execute command I've passed in argument but the command does not executes.

As #mtijn said you've got a lot going on that you're also overriding later. You also need to make sure that you're escaping things correctly.
Let's say that you want to run the following command elevated:
dir c:\
First, if you just ran this command through Process.Start() a window would pop open and close right away because there's nothing to keep the window open. It processes the command and exits. To keep the window open we can wrap the command in separate command window and use the /K switch to keep it running:
cmd /K "dir c:\"
To run that command elevated we can use runas.exe just as you were except that we need to escape things a little more. Per the help docs (runas /?) any quotes in the command that we pass to runas need to be escaped with a backslash. Unfortunately doing that with the above command gives us a double backslash that confused the cmd parser so that needs to be escaped, too. So the above command will end up being:
cmd /K \"dir c:\\\"
Finally, using the syntax that you provided we can wrap everything up into a runas command and enclose our above command in a further set of quotes:
runas /env /user:Administrator "cmd /K \"dir c:\\\""
Run the above command from a command prompt to make sure that its working as expected.
Given all that the final code becomes easier to assemble:
//Assuming that we want to run the following command:
//dir c:\
//The command that we want to run
string subCommand = #"dir";
//The arguments to the command that we want to run
string subCommandArgs = #"c:\";
//I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
//Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
string subCommandFinal = #"cmd /K \""" + subCommand.Replace(#"\", #"\\") + " " + subCommandArgs.Replace(#"\", #"\\") + #"\""";
//Run the runas command directly
ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
//Create our arguments
string finalArgs = #"/env /user:Administrator """ + subCommandFinal + #"""";
procStartInfo.Arguments = finalArgs;
//command contains the command to be executed in cmd
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
}

why are you initializing the process object with arguments and then later on override those Arguments? and btw: the last bit where you set Arguments you concatenate 'command' right upto 'cmd', that doesn't make much sense and might be where it fails (looks like you're missing a space).
Also, you are currently using the standard command line, you might want to look into using the runas tool instead. you can also call runas from command line.
Also, why are you running 'command' from the command line? why not start it directly from Process.Start with admin privileges supplied then and there? here's a bit of pseudocode:
Process p = Process.Start(new ProcessStartInfo()
{
FileName = <your executable>,
Arguments = <any arguments>,
UserName = "Administrator",
Password = <password>,
UseShellExecute = false,
WorkingDirectory = <directory of your executable>
});

Related

Maintaining variables when executing cmd from C# application

I want to call some cmd prompt commands from a .net C# application. However before the command is run I need to set up a varaibles within a batch file. Is there a way to maintain the variables to subsequent calls to the command prompt?
I provide an example below of the problem.
Say I have a simple batch file C:\setEnv.bat containing
set notepad=C:\windows\system32\notepad.exe
Then if I have C# code like thus:
var proc1 = new ProcessStartInfo();
string cmd1 = #"CALL C:\setEnv.bat";
string cmd2 = #"ECHO notepad=%notepad%>C:\test.txt";
proc1.UseShellExecute = true;
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C " +cmd1;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
startInfo.Arguments = "/C " + cmd2;
process.Start();
process.WaitForExit();
Now I'm guessing that the /C is terminating the command prompt thus losing my variables but if I don't have it then the cmd prompt doesn't return after finishing the command.
I thought I could double the cmd1 & cmd2 to a single call but then I would need to do that for every call to the cmd prompt and feels a little redundant calling C:\setenv.bat again and again.
You may use way in this question
For example, use command "set" in cmd1:
string cmd1 = "\" CALL C:\\setEnv.bat && set \"";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
//...
process.Start();
string variables = process.StandardOutput.ReadToEnd();
// next parse variables string
And before start second process set parsed variables in "startInfo.EnvironmentVariables"
A few issues/ideas:
1) How many values to you need to track from one execution to the next? Primarily, can you just use the errorlevel return value or do you need more details?
2) Can you pipe the results of the first directly into the second as one call?
3) Can you output the values from the first call to a file and in the 2nd call, pipe that as input into the 2nd cmd?
4) I assume that you have some processing that is done after the first cmd is run, but before the 2nd cmd is called. Could you create an .exe that can be called by the 1st batch file (after the other code) that does that processing. That way, you have 3 cmds all of which can be run in the same environment and your variables stick around.

Run cmd command using "runas" with credentials in C#

Similar question was asked at least a dozen times on SO and it looks that now I have exhausted most of the proposed solutions but still unable to complete the task successfully.
So what I have is the following command that I want to run in cmd:
xcopy /q C:\fileName.txt \\VMNAME\C$\destFolder /Y /E
But I need it to be executed with certain credentials. So what I was doing manually is entering the below command first:
runas /user:<domainName>\<userName> cmd
That was opening a separate cmd window and I was running the first (xcopy) command in that window.
What I have at the moment:
string strCmdText = string.Format(#"xcopy /q {0} {1} /Y /E", source, destination);
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.FileName = "runas";
procStartInfo.Arguments = String.Format(#"/user:<domainName>\<userName> cmd " + strCmdText);
Process.Start(procStartInfo);
Where the source and destination are of the below structure:
source = "C:\\somePath\\fileName.txt"
destination = "\\\\<VMName>\\C$\\somePath\\"
I have also tried defining procStartInfo with:
procStartInfo.Verb = "runas";
Instead of:
procStartInfo.FileName = "runas";
With similar results.
At the moment, when I run the above code, it does not return any error but doesn't do what's expected either. Am I missing something or this approach is wrong?

How to pause cmd before it close?

This is my code
System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
proc.FileName = #"cmd.exe";
proc.Arguments = "/C "+ "ipconfig" ;
System.Diagnostics.Process.Start(proc);
when I run this code , Cmd run and shut down so quickly .
How to pause it ?
THANKS A LOT :)
Specify the K parameter instead of C
From Microsoft documentation:
/c : Carries out the command specified by string and then stops.
/k : Carries out the command specified by string and continues.
proc.Arguments = "/K "+ "ipconfig" ;
more info: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true
Use /K instead of /C.
proc.Arguments = "/K " + "ipconfig";
You can see a list of command line switches here
/C Run Command and then terminate
/K Run Command and then return to the CMD prompt.
This is useful for testing, to examine variables

Spawning command prompt app in CMD window in C#

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.

Running cmd commands via .NET?

System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;
And now for some background...
string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
omgwut is something like this:
copy /b a.wav + b.wav + ... + y.wav + z.wav output.wav
And nothing happens at all. So obviously something's wrong. I also tried "copy" as the executable, but that doesn't work.
Try the prefixing your arguments to cmd with /C, effectively saying cmd /C copy /b t.wav ...
According to cmd.exe /? using
/C <command>
Carries out the command specified by
string and then terminates
For your code, it might look something like
// ..
proc0.StartInfo.Arguments = "/C " + omgwut;
Notes:
A good way to test whether your command is going to work is to actually try it from a command prompt. If you try to do cmd.exe copy ... you'll see that the copy doesn't occur.
There are limits to the length of the arguments you can pass as arguments. From MSDN: "The maximum string length is 2,003 characters in .NET Framework applications and 488 characters in .NET Compact Framework applications."
You can bypass the shelling out to command by using the System.IO classes to open the files and manually concatenate them.
Try this it might help you.. Its working with my code.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}
Even you can try this.. this is even better.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments="http://www.microsoft.com";
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited " + proc.StartInfo.Arguments);
Daniels cmd /c idea will work. Keep in mind there is a limit to the length of a command line probably 8k in your case see this for details.
Since you are in a .Net app anyway, File.Copy may be quite a bit easier/cleaner than this approach.

Categories