DNK Gif

Dot Net Knowledge

Labels

Sunday, 17 April 2016

Execute .bat file in a remote Computer using C#

How to Execute a batch file or script in a remote Computer or Server using C#?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace RemoteApplicationExecution
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ConnectionOptions options =new ConnectionOptions();
                options.Authority = "ntlmdomain:INDIA";
                options.Username = "740471";
                options.Password = "Apr@2016";
                ManagementScope scope =
                    new ManagementScope(
                    "\\\\01hw894947\\root\\cimv2",options);
                var processToRun = new[] { @"C:\test\Start-Stop.bat" };
                scope.Connect();
                //Query system for Operating System information
                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM Win32_OperatingSystem");
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(scope, query);

                ManagementObjectCollection queryCollection = searcher.Get();
                foreach (ManagementObject m in queryCollection)
                {
                    // Display the remote computer information
                    Console.WriteLine("Computer Name : {0}",
                        m["csname"]);
                    Console.WriteLine("Windows Directory : {0}",
                        m["WindowsDirectory"]);
                    Console.WriteLine("Operating System: {0}",
                        m["Caption"]);
                    Console.WriteLine("Version: {0}", m["Version"]);
                    Console.WriteLine("Manufacturer : {0}",
                        m["Manufacturer"]);
                }
                var wmiProcess = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
                wmiProcess.InvokeMethod("Create", processToRun);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.Source + Environment.NewLine + ex.InnerException + ex.StackTrace);
                throw ex;
            }
        }
    }
}


1 comment:

  1. Note: Please add System.Management dll from your assembly in the reference. No need to download any third party dlls.

    ReplyDelete