简体   繁体   中英

Execute .bat File on a Server in C#

I am attempting to execute a .bat file on a remote machine (a server) that ends a process and kicks the user out of a database system. When executed on the server, the file works correctly and ends the process on the client machine.

However, when executed through C#, the command is entered into the command prompt and cannot execute. Here is the .bat file;

psexec \\lp-100 msg * Hi Dan - your being removed!

pskill \\lp-100 sdcdatabase.vshost.exe

pause

The issue arises when executed in C#, this is the error message:

在此处输入图片说明

What this leads me to believe is that actually the .bat file is not being executed on the server (that does have PsTools installed), but instead the contents is being copied over and executed on the client machine instead.

Here is the code I am using to execute the .bat file;

Process proc = null;
try
{
    string batDir = string.Format(@"\\hqdb1\sdc_sqldb\pstools\");
    proc = new Process();
    proc.StartInfo.WorkingDirectory = batDir;
    proc.StartInfo.FileName = "removeuser.bat";
    proc.StartInfo.CreateNoWindow = false;
    proc.Start();
    proc.WaitForExit();
    MessageBox.Show("Bat file executed !!");
}
catch (Exception ex)
{
    Console.WriteLine(ex.StackTrace.ToString());
}

Is this executing the .bat file on the server, kicking the client off, or executing on the client and not finding PsTools ?

Years ago I wrote this code, try if it's still working:

ConnectionOptions options = new ConnectionOptions();
options.Password = args[2];
options.Username = args[1];
string machine= args[0];

ManagementScope scope = new ManagementScope();
scope.Options = options;
scope.Path = new ManagementPath(@"\\" + machine + @"\root\cimv2");
scope.Connect();

ObjectQuery query = new ObjectQuery("Select * from Win32_Process Where Name     = '" + args[3] + "'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
    object y = m.GetPropertyValue("ProcessID");
    int pID = Convert.ToInt32(y);
    m.InvokeMethod("Terminate", null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM