Create a forms app to restart a remote PC - c#

I just need to create a tool to restart a specific windows device in our city offices. which will always in 192.168.cityID.33 I have found a way to detect the citycode portion of the IP and to add 33 to it in GetIPMethod.
thee mentioned device have different set of username and password im having issues passing the restart command to the cmd
PS: I'm not a full time developer i'm just a network admin who tries to reduce my daily work load :)
Thanks in advance
public void Command1()
{
String IP = GetIPAddress().ToString();
string NewIP = IP.Substring(0, IP.LastIndexOf("."));
string TOPIP = NewIP + ".33";
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StandardInput.WriteLine("NET USE \\" + TOPIP + "\receiver /USER:GenusDS G3nu5DS");
process.StandardInput.WriteLine("shutdown /m \\" + TOPIP + " /r /f -t 00");
process.Start();
process.StandardInput.Flush();
process.Close();
process.WaitForExit();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.ReadKey();
string strCmdText;
strCmdText = "NET USE \\" + TOPIP + "\receiver /USER:GDS G3nS";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
}
public static IPAddress GetIPAddress()
{
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address =>
address.AddressFamily == AddressFamily.InterNetwork).First();
return ip;
}

I normally do something similar to below:
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C net use \\[My IP] [My Password] /USER:[My Username]";
process.StartInfo = startInfo;
Process.Start(startInfo);
And this question shows how to run multiple commands in one process.
Hope that helps.

var proc1 = new ProcessStartInfo();
string Command;
proc1.UseShellExecute = true;
Command = "net use " + slash + TOPIP + "\\receiver /user:GenusDS G3nu5DS&shutdown /m " + slash + TOPIP + " /r /f -t 00";
proc1.WorkingDirectory = #"C:\Windows\System32";
proc1.FileName = #"C:\Windows\System32\cmd.exe";
/// as admin = proc1.Verb = "runas";
proc1.Arguments = "/c " + Command;
proc1.WindowStyle = ProcessWindowStyle.Maximized;
Process.Start(proc1);

Related

Run a Process silently in background without any window

I want to run NETSH command silently (with no window).
I wrote this code but it does not work.
public static bool ExecuteApplication(string Address, string workingDir, string arguments, bool showWindow)
{
Process proc = new Process();
proc.StartInfo.FileName = Address;
proc.StartInfo.WorkingDirectory = workingDir;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.CreateNoWindow = showWindow;
return proc.Start();
}
string cmd= "interface set interface name=\"" + InterfaceName+"\" admin=enable";
ExecuteApplication("netsh.exe","",cmd, false);
This is how I do it in a project of mine:
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "netsh";
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.Arguments = "SOME_ARGUMENTS";
Process proc = Process.Start(psi);
proc.WaitForExit();
string errorOutput = proc.StandardError.ReadToEnd();
string standardOutput = proc.StandardOutput.ReadToEnd();
if (proc.ExitCode != 0)
throw new Exception("netsh exit code: " + proc.ExitCode.ToString() + " " + (!string.IsNullOrEmpty(errorOutput) ? " " + errorOutput : "") + " " + (!string.IsNullOrEmpty(standardOutput) ? " " + standardOutput : ""));
It also accounts for the outputs of the command.
Make user shell execution false
proc.StartInfo.UseShellExecute = false;
and pass true in showWindow parameter
ExecuteApplication("netsh.exe","",cmd, true);

run command promt application from code C#

This is my code:
var startupPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName; // +\\Common
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments ="/c " + startupPath + #"\Common\sound 1.wav result.wav -tempo=35";
process.StartInfo = startInfo;
process.Start();
Pathes are correct. A wanna to start application and set this parameters sound 1.wav result.wav -tempo=35. What am I doing wrong?
content of startInfo.Arguments:
"/c C:\\SOUNDS\\New folder\\TrunscribeHelper\\Common\\sound 1.wav result.wav -tempo=35"
I've tryed to start it directly:
ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(startupPath + #"\Common", "\\", "sound.exe"));
startInfo.Arguments = "1.wav result.wav -tempo=35";
startInfo.UseShellExecute = false;
System.Diagnostics.Process.Start(startInfo);
But Am I doing wrong now?
Your have to set your path in the args under double quotes:
"/c \"C:\\SOUNDS\\New folder\\TrunscribeHelper\\Common\\sound 1.wav\" result.wav -tempo=35"
Can you try changing this line:
startInfo.Arguments ="/c " + startupPath + #"\Common\sound 1.wav result.wav -tempo=35";
to
startInfo.Arguments ="/c \"" + startupPath + #"\Common\sound"" 1.wav result.wav -tempo=35";

C# run batch file with argument with spaces

I need to run batch file, which has path (can contains spaces) as argument.
Batch file is really simple:
echo off
echo %1 > echotest.txt
Csharp code I am using to run this batch file:
ProcessStartInfo info = new ProcessStartInfo();
info.UserName = KIM_USER;
info.Password = ConvertToSecureString(KIM_USER_PASSWORD);
info.FileName = theTask.Path;
info.Arguments = "\"" + TranslateParameter(theTask.Parameter) + "\"";
info.Domain = Environment.MachineName;
info.WorkingDirectory = Path.GetDirectoryName(theTask.Path);
info.UseShellExecute = false;
info.CreateNoWindow = true;
Process batProcess = Process.Start(info);
batProcess.WaitForExit();
Basically in parameter comes e.g {Test_Path} and this is in TranslateParameter converted to real path, e.g: D:\Test Path\ (contains spaces)
This does not work for me, it returns me exit code 1 everytime.
If i remove \" from info.Arguments, it works, but in output file is just D:\Test
Any suggestions?
Regards
Can you try this if that works:
ProcessStartInfo info = new ProcessStartInfo();
info.UserName = KIM_USER;
info.Password = ConvertToSecureString(KIM_USER_PASSWORD);
info.FileName = theTask.Path + " \"" + TranslateParameter(theTask.Parameter) + "\"";
//info.Arguments = "\"" + TranslateParameter(theTask.Parameter) + "\"";
info.Domain = Environment.MachineName;
info.WorkingDirectory = Path.GetDirectoryName(theTask.Path);
info.UseShellExecute = false;
info.CreateNoWindow = true;
Process batProcess = Process.Start(info);
batProcess.WaitForExit();

Multiple arguments with cmd.exe via a C# Process

I try to call the esriRegAsm.exe with arguments from a C# program.
The purpose is to register a Dll. Therefore I usually call the esriRegAsm.exe with the Dll as argument plus some additional parameters (/p:Desktop /s). This works fine if I type it into cmd.exe. Somehow I think that the process sends only the first string to the cmd and not the whole argument list, but I need the "" for the space character in the paths.
For debugging I added a message box and the strings seems to be okay.
Backslash or double backslash seems to be unimportant.
string targetDir = this.Context.Parameters["targ"];
string programFilesFolder = this.Context.Parameters["proFiles"];
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C \"" + programFilesFolder + "Common Files\\\\ArcGIS\\\\bin\\\\esriRegAsm.exe\" " + "\"" + targetDir + "RArcGISTest.dll\" /p:Desktop /s";
MessageBox.Show("/C \"" + programFilesFolder + "Common Files\\\\ArcGIS\\\\bin\\\\esriRegAsm.exe\" " + "\"" + targetDir + "RArcGISTest.dll\" /p:Desktop /s");
process.StartInfo = startInfo;
process.Start();
As I cannot attache a picture of the message box... the output is:
/C "C:\Program Files (x86)\Common Files\ArcGIS\bin\esriRegAsm.exe" "C:\install\RArcGISTest.dll" /p:Desktop /s"
Why are you double-escaping things, and why are you routing it through cmd.exe? Just execute the process directly:
string targetDir = this.Context.Parameters["targ"];
string programFilesFolder = this.Context.Parameters["proFiles"];
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = Path.Combine(programFilesFolder, #"Common Files\ArcGIS\bin\esriRegAsm.exe");
startInfo.Arguments = "\"" + Path.Combine(targetDir, "RArcGISTest.dll") + "\" /p:Desktop /s";
process.StartInfo = startInfo;
process.Start();

Execute command line using C#

All I am trying to do is send a command that opens a model with the program.exe
Supposed to be super simple!
Ex:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
The line above works well if pasted on the command prompt window.
However, when trying to pass the same exact string on my code it gets stuck on C:\Program
string EXE = "\"" + #tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + #mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel is showing te following line on Visual Studio:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
To me looks like it is the string I need to send in to the following method:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
Things I've tried:
Pass only one command at a time (works as expected), but not an option since the model file will open with another version of the software.
Tried to Trim
Tried with # with \"
Can anyone see any obvious mistake? Thanks.
It's pretty straightforward. You just create a command line object then write to it, then to execute it you read back from it using SR.ReadToEnd():
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("#echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
Why are you opening a command prompt (cmd.exe)? Just pass the name of the executable.

Categories

Resources