I'm starting a Process using a special User, Domain and Password. Although I told C# to hide the console window it is shown.
Here my code:
Process process = new Process();
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UserName = strUsername;
process.StartInfo.Domain = strDomain;
process.StartInfo.Password = secPassword;
process.StartInfo.FileName = "PsExec.exe";
process.StartInfo.Arguments = #"/accepteula -s \\" + strServername + #"program.exe";
process.Start();
process.WaitForExit();
I could find some hints in another forum:
If you call the Start(ProcessStartInfo) method with the
ProcessStartInfo..::.UserName and ProcessStartInfo..::.Password
properties set, the unmanaged CreateProcessWithLogonW function is
called, which starts the process in a new window even if the
CreateNoWindow property value is true or the WindowStyle property
value is Hidden.
Actually, I'm not really satisfied with this statement...
Thanks in advance.
Cheers
Alex
As i know there are workaround on this issue. You can launch hidden cmd with your params. Something like this:
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", String.Format("/accepteula -s \\{0}program.exe", strServername));
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process.Start(psi);
using (Process LMUTIL = new Process())
{
string arg1 ="argument"
LMUTIL.StartInfo.FileName = "program.exe";
LMUTIL.StartInfo.Arguments = arg1
LMUTIL.StartInfo.UseShellExecute = false;
LMUTIL.StartInfo.RedirectStandardOutput = true;
LMUTIL.StartInfo.CreateNoWindow = true;
LMUTIL.EnableRaisingEvents = true;
LMUTIL.OutputDataReceived += p_WriteData;
LMUTIL.Start();
LMUTIL.BeginOutputReadLine();
}
private void p_WriteData(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Debug.WriteLine(e.Data.ToString());
}
}
I lifted this straight out of a project that does what you need. Subscribe to the p_WriteData event to capture what would appear in the command window.
After all, it is not possible to hide this psexec console window using the Process Class.
It's not necessary to use psexec. I used the WMI stuff instead:
ConnectionOptions remoteConnectionOptions = new ConnectionOptions();
remoteConnectionOptions.Impersonation = ImpersonationLevel.Impersonate;
remoteConnectionOptions.EnablePrivileges = true;
remoteConnectionOptions.Authentication = AuthenticationLevel.Packet;
remoteConnectionOptions.Username = strDomain + #"\" + strUsername;
remoteConnectionOptions.SecurePassword = secPassword;
ManagementScope scope = new ManagementScope(#"\\" + strServername + #"\root\CIMV2", remoteConnectionOptions); ManagementPath p = new ManagementPath("Win32_Process");
ManagementClass classInstance = new ManagementClass(scope, p, null); object[] theProcessToRun = { "myExecutable.exe" };
classInstance.InvokeMethod("Create", theProcessToRun);
Related
I'm running the below command from c#. There is a prompt that will be shown that I want to answer "yes" to how can I do this with the current code
If I run this as a batch script I can just do
echo y | pscp.exe -batch -pw password E:\\Certs\\client.conf me#<ip>:/home/user
which works - but unsure how I can replicate this using the below
string pscpPath="-batch -pw password E:\\Certs\\client.conf me#<ip>:/home/user";
ExecuteCopyCerts("pscp.exe", pscpPath);
Function:
public Boolean ExecuteCopyCerts(string fileName, string arguments)
{
txtLiveHubStatus.Text = "";
try
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
return proc.ExitCode == 0;
}
}
Set RedirectStandardInput to true
procStartInfo.RedirectStandardInput = true
and then write to StandardInput
proc.StandardInput.WriteLine("yes");
To reiterate what Hesam said though the prompt is Y, not yes. This is the prompt for the cert, which only occurs on the first call to each new linux machine. I use this code today in one of our applications.
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "pscp";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = $"-r -p -pw {passWord} \"{localFileNamePath}\" {userName}#{hostName}:{remotePath}";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
using (Process process = new Process())
{
process.StartInfo = psi;
process.Start();
process.StandardInput.WriteLine("Y");
process.WaitForExit();
}
I want to run visual studios command programmatically.I have tried the above code but no help.All I am getting is a command prompt with my project`s directory open.
I have used Execute("VS140COMNTOOLS") as input.
private void Execute(string vsEnvVar) {
var vsInstallPath = Environment.GetEnvironmentVariable(vsEnvVar);
if (Directory.Exists(vsInstallPath)) {
var filePath = vsInstallPath + "vsvars32.bat";
if (File.Exists(filePath)) {
//start vs command process
Process proc = new Process();
var command = Environment.GetEnvironmentVariable("ComSpec");
command = #"" + command + #"";
//var batfile = #"E:\Test\vstest.bat";
var args = string.Format("/S/K \" \"{0}\" \"", filePath);
proc.StartInfo.FileName = command;
proc.StartInfo.Arguments = args;
//proc.StartInfo.RedirectStandardInput = true;
//proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
} else {
Console.WriteLine("File Does not exists " + filePath);
}
}
}
Try this:
private Process Execute(string vsEnvVar)
{
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");//assume location is in path. Otherwise use ComSpec env variable
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo = psi;
// attach output events
process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.StartInfo = psi;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.StandardInput.WriteLine(string.Format("call \"%{0}%vsvars32.bat\""), vsEnvVar);
process.StandardInput.Flush();
return process;
}
Now you can execute any commands by writing to process.StandardInput
process.StandardInput.WriteLine(#"msbuild c:\MySolution.sln /t:Clean");
I need a windows activate method. My code works, but it create a popup window and I don't want it.
Is there any way to activate in background without any message?
private void tryingActivateWindows()
{
ProcessStartInfo psi = new ProcessStartInfo("cmd", "/c " + "SLMGR -ato");
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
}
private void tryingActivateWindows()
{
Process activateScript = new Process();
activateScript.StartInfo.FileName = #"cscript";
activateScript.StartInfo.WorkingDirectory = #"C:\Windows\System32\";
activateScript.StartInfo.Arguments = "//B //Nologo slmgr.vbs -ato";
activateScript.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
activateScript.Start();
activateScript.WaitForExit();
}
Run "cscript C:\Windows\System32\slmgr.vbs /ato"
It will prevent the pop-up.
Building a console app that will execute an exe file(pagesnap.exe). I would like to hide its window(pagesnap.exe) during execution. How is it done.
ProcessStartInfo Psi = new ProcessStartInfo("D:\\PsTools\\");
Psi.FileName = "D:\\PsTools\\psexec.exe";
Psi.Arguments = #"/C \\DESK123 D:\files\pagesnap.exe";
Psi.UseShellExecute = false;
Psi.RedirectStandardOutput = true;
Psi.RedirectStandardInput = true;
Psi.WindowStyle = ProcessWindowStyle.Hidden;
Psi.CreateNoWindow = true;
Process.Start(Psi).WaitForExit();
DESK123 is the local PC. Would later try this with remote PCs.
Things I have tried
Psi.Arguments = #"/C start /b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 /b D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 D:\files\pagesnap.exe 2>&1 output.log";
Update: I have built pagesnap with Output type as a windows application instead of console. The cmd window doesn't come up, now. Seems this is the only way for me
Simply call the following function. Pass the argument as your command and your working directory
private string BatchCommand(string cmd, string mapD)
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd);
procStartInfo.WorkingDirectory = mapD;
// 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.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = 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 cmdProcess = new System.Diagnostics.Process();
cmdProcess.StartInfo = procStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping www.google.com"); //Execute ping
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
// Get the output into a string
return Batchresults;
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
Batchresults += Environment.NewLine + e.Data.ToString();
}
void cmd_Error(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Batchresults += Environment.NewLine + e.Data.ToString();
}
}
I'm working on a custom IDE in C# for a scripting language, and I have a problem.
I'm trying to start the compiler process (pawncc.exe) and pass arguments to it. I've done that, and now I have a problem. When I want to display the output from the compiler application, it only displays some parts of it. It should output this (got this from the command prompt):
Pawn compiler 3.2.3664 Copyright (c) 1997-2006, ITB CompuPhase
newGM.pwn(0) : fatal error 100: cannot read from file: "includes/main_include.inc"
Compilation aborted.
1 Error.
But it doesn't. It outputs this (in the application, using the same command/arguments):
Pawn compiler 3.2.3664 Copyright (c) 1997-2006, ITB CompuPhase
1 Error.
I just don't get it! It's a really weird thing. It might be something simple but I've been looking at it, and researching for hours now! Here's my code:
public Form3(string path)
{
InitializeComponent();
this._path = path;
Process myProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("pawncc.exe");
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = path + " -r -d2";
myProcess.StartInfo = startInfo;
myProcess.Start();
while (true)
{
string myString;
byte[] buffer = new byte[512];
var ar = myProcess.StandardOutput.BaseStream.BeginRead(buffer, 0, 512, null, null);
ar.AsyncWaitHandle.WaitOne();
var bytesRead = myProcess.StandardOutput.BaseStream.EndRead(ar);
if (bytesRead > 0)
{
myString = Encoding.ASCII.GetString(buffer, 0, bytesRead);
}
else
{
myProcess.WaitForExit();
break;
}
richTextBox1.Text = myString;
}
}
!!EDIT:
It does the same thing with this code:
public Form3(string path)
{
InitializeComponent();
this._path = path;
Process myProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("pawncc.exe");
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.Arguments = path + " -r -d2";
myProcess.StartInfo = startInfo;
myProcess.Start();
using (StreamReader reader = myProcess.StandardOutput)
{
string result = reader.ReadToEnd();
richTextBox1.Text = result;
}
}
You need to redirect the standard error stream as well:
startInfo.RedirectStandardError = true;
Edit: I just reviewed the code and discovered that you are only readonly the StandardOutput stream.
I generally monitor the process for both the standard and error output streams using the DataReceived events on the process and adding the results into a stringbuilder, then storing the StringBuilder content in the UI element:
private static System.Text.StringBuilder m_sbText;
public Form3(string path)
{
InitializeComponent();
this._path = path;
Process myProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("pawncc.exe");
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.Arguments = path + " -r -d2";
myProcess.StartInfo = startInfo;
m_sbText = new System.Text.StringBuilder(1000);
myProcess.OutputDataReceived += ProcessDataHandler;
myProcess.ErrorDataReceived += ProcessDataHandler;
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
while (!myProcess.HasExited)
{
System.Threading.Thread.Sleep(500);
System.Windows.Forms.Application.DoEvents();
}
RichTextBox1.Text = m_sbText.ToString();
}
private static void ProcessDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
// Collect the net view command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
// Add the text to the collected output.
m_sbText.AppendLine(outLine.Data);
}
}
There are obviously variations on this, but this should get you started.
I dont have the pawnCC application so I cant try but it appears they restrict the verbosity of debugging information to external applications - apart from the command prompt.
Can you try spawning the pawncc.exe via cmd:
"cmd.exe \c CommandParameterToLaunchPawnCCwithArguments"
I've noticed some sporadic issues when dealing with the raw output/error streams from spawned processes in the past, hence why I usually deal with captured output via eventing:
Process myProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("pawncc.exe");
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.Arguments = path + " -r -d2";
myProcess.EnableRaisingEvents = true;
myProcess.OutputDataReceived += OnOutputDataReceived;
myProcess.ErrorDataReceived += OnErrorDataReceived;
myProcess.StartInfo = startInfo;
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();