Пример #1
0
        private string FormEventString(ManagementBaseObject eventObj)
        {
            string text = Label + ": " + eventObj.GetText(TextFormat.Mof);

            text = text.Replace("\r", "");
            return(text.Replace("\n", " "));
        }
Пример #2
0
        public static int Main(string[] args)
        {
            ManagementClass processClass = new ManagementClass("Win32_Process");

            // Create a watcher and completion handler
            ManagementOperationWatcher watcher    = new ManagementOperationWatcher();
            ObjectReadyHandler         objHandler = new ObjectReadyHandler();

            watcher.ObjectReady += new ObjectReadyEventHandler(objHandler.NewObject);

            // Invoke using parameter instances
            ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

            inParams.Properties["CommandLine"].Value = "calc.exe";
            processClass.InvokeMethod(watcher, "Create", inParams, null);

            while (!objHandler.IsComplete)                              //Infinite loop here
            {
                System.Threading.Thread.Sleep(1000);
            }
            objHandler.Reset();

            ManagementBaseObject o = objHandler.ReturnObject;

            Console.WriteLine(o.GetText(TextFormat.MOF));
            Console.WriteLine("Creation of calculator process returned: " + o["returnValue"]);
            Console.WriteLine("Process id: " + o["processId"]);

            return(0);
        }
Пример #3
0
        private bool LeaveDomain()
        {
            // Invoke WMI to join the domain
            using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
            {
                try
                {
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = wmiObject.GetMethodParameters("UnJoinDomainOrWorkgroup");

                    inParams["FJoinOptions"] = 0;

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);

                    //_connect_to_domain_result = (int)outParams["ReturnValue"];

                    if (int.TryParse(outParams["ReturnValue"].ToString(), out _connect_to_domain_result))
                    {
                        return(_connect_to_domain_result == 0);
                    }
                    else
                    {
                        MessageBox.Show(outParams.GetText(TextFormat.Mof));
                        _connect_to_domain_result = 4;
                        return(false);
                    }
                }
                catch (ManagementException e)
                {
                    //_connect_to_domain_result = 4;
                    return(false);
                }
            }
        }
Пример #4
0
        public static void SetPropertyValue(ManagementBaseObject wmiClass, string propertyName, object value)
        {
            const string method = "SetPropertyValue";

            if (wmiClass == null)
            {
                throw new NullParameterException(typeof(WmiUtil), method, "wmiClass");
            }
            if (propertyName == null)
            {
                throw new NullParameterException(typeof(WmiUtil), method, "propertyName");
            }

            try
            {
                wmiClass.SetPropertyValue(propertyName, value);
            }
            catch (ManagementException ex)
            {
                string classText = null;
                try
                {
                    classText = wmiClass.GetText(TextFormat.Mof);
                }
                catch (System.Exception)
                {
                }

                throw new WmiPropertySetException(typeof(WmiUtil), method, propertyName,
                                                  wmiClass.ClassPath.ToString(), classText, value, ex);
            }
        }
Пример #5
0
        private void HandleEvent(object sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject info = e.NewEvent;


            log.Info("Event arrived ! " + info.ClassPath);
            log.Debug(info.GetText(TextFormat.Mof));
        }
Пример #6
0
 public override string ToString()
 {
     if (_managementObject != null)
     {
         return(_managementObject.GetText(TextFormat.Mof));
     }
     return(base.ToString());
 }
        private void Watcher_EventArrived(object?sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject o = (ManagementBaseObject)e.NewEvent["TargetInstance"];

            LOG.Debug($"{nameof( Watcher_EventArrived )} - Object: {o.GetText( TextFormat.Mof )}");

            CheckTortoiseGitProcessObject(o);
        }
Пример #8
0
    static void Mainx()
    {
        // Get a ManagementClass and ManagementObject to serialize
        ManagementClass  cls = new ManagementClass("__Win32Provider");
        ManagementObject obj = new ManagementObject("root:__Namespace='cimv2'");

        // Show the info we want to serialize
        Console.WriteLine("*** INITIAL CLASS PROPERTIES AND VALUES");
        foreach (PropertyData prop in cls.Properties)
        {
            Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
        }
        Console.WriteLine("*** INITIAL CLASS MOF");
        Console.WriteLine(cls.GetText(TextFormat.Mof));
        Console.WriteLine("*** INITIAL OBJECT PROPERTIES AND VALUES");
        foreach (PropertyData prop in obj.Properties)
        {
            Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
        }
        Console.WriteLine("*** INITIAL OBJECT MOF");
        Console.WriteLine(obj.GetText(TextFormat.Mof));

        //Open a file and serialize a ManagementClass and a ManagementObject into the file
        Stream          stream     = File.Open("MyClass1MyClass2.bin", FileMode.Create);
        BinaryFormatter bformatter = new BinaryFormatter();

        bformatter.Serialize(stream, cls);
        bformatter.Serialize(stream, obj);
        stream.Close();

        //Open file "MyClass1MyClass2.bin" and deserialize the MyClass1 object from it.
        stream     = File.Open("MyClass1MyClass2.bin", FileMode.Open);
        bformatter = new BinaryFormatter();
        ManagementBaseObject baseObject1 = (ManagementBaseObject)bformatter.Deserialize(stream);
        ManagementBaseObject baseObject2 = (ManagementBaseObject)bformatter.Deserialize(stream);

        stream.Close();

        // Show the Deserialized information
        Console.WriteLine("*** DESERIALIZED CLASS PROPERTIES AND VALUES");
        foreach (PropertyData prop in baseObject1.Properties)
        {
            Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
        }
        Console.WriteLine("*** DESERIALIZED CLASS MOF");
        Console.WriteLine(baseObject1.GetText(TextFormat.Mof));
        Console.WriteLine("*** DESERIALIZED OBJECT PROPERTIES AND VALUES");
        foreach (PropertyData prop in baseObject2.Properties)
        {
            Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
        }
        Console.WriteLine("*** DESERIALIZED OBJECT MOF");
        Console.WriteLine(baseObject2.GetText(TextFormat.Mof));
    }
Пример #9
0
        private void ExecuteMethod()
        {
            string returnString = String.Empty;

            try
            {
                this.Cursor = Cursors.WaitCursor;
                SetStatusBar("Executing method...", MessageCategory.Action);

                ManagementBaseObject inParams = _mObject.GetMethodParameters(_method.Name);

                foreach (Control control in panelInParams.Controls)
                {
                    if (control is TextBox)
                    {
                        inParams[control.Tag.ToString()] = control.Text;
                    }

                    if (control is CheckBox)
                    {
                        inParams[control.Tag.ToString()] = ((CheckBox)control).Checked.ToString();
                    }
                }

                ManagementBaseObject outParams = _mObject.InvokeMethod(_method.Name, inParams, null);

                if (outParams != null && outParams.Properties.Count > 0)
                {
                    ManagementBaseObjectW outParamsW = new ManagementBaseObjectW(outParams);
                    propertyGridOutParams.SelectedObject = outParamsW;
                    _clipboardText = outParams.GetText(TextFormat.Mof).Replace("\n", "\r\n");
                    SetStatusBar("Successfully executed method.", MessageCategory.Info);
                }
                else
                {
                    SetStatusBar("Successfully executed method. No output parameters.", MessageCategory.Info);
                }

                returnString = "Successfully executed method " + _method.Name + " of object " + _mObject.Path.RelativePath;
            }
            catch (Exception ex)
            {
                SetStatusBar("Method Execution Failed. Error: " + ex.Message, MessageCategory.Error);
                returnString = "Failed to execute method " + _method.Name + " of object " + _mObject.Path.RelativePath + ". Error: " + ex.Message;
            }
            finally
            {
                WmiExplorer parentForm = (WmiExplorer)this.Owner;
                parentForm.Log(returnString);
                this.Cursor = Cursors.Default;
            }
        }
Пример #10
0
        /// <summary>
        /// 定位发生插拔的USB设备
        /// </summary>
        /// <param name="e">USB插拔事件参数</param>
        /// <returns>发生插拔现象的USB控制设备ID</returns>
        public static List <USBControllerDevice> WhoUSBControllerDevice(EventArrivedEventArgs e)
        {
            ManagementBaseObject mbo = e.NewEvent["TargetInstance"] as ManagementBaseObject;

            if (mbo != null && mbo.ClassPath.ClassName == "Win32_USBControllerDevice")
            {
                LOG.Info(mbo.GetText(TextFormat.WmiDtd20));
                LOG.Info(mbo.GetText(TextFormat.CimDtd20));
                LOG.Info(mbo.GetText(TextFormat.Mof));

                String Antecedent = (mbo["Antecedent"] as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1];
                String Dependent  = (mbo["Dependent"] as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1];
                return(new List <USBControllerDevice>(1)
                {
                    new USBControllerDevice {
                        Antecedent = Antecedent, Dependent = Dependent
                    }
                });
            }

            return(null);
        }
Пример #11
0
        public void ImportVirtualSystem(string importDirectory, string newMachineName, string machineLocation)
        {
            var scope = new ManagementScope(@"\\" + host + @"\root\virtualization", null);

            using (ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService"))
            {
                ManagementBaseObject importSettingData = GetVirtualSystemImportSettingData(
                    scope, importDirectory, newMachineName, machineLocation);

                using (ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("ImportVirtualSystemEx"))
                {
                    inParams["ImportDirectory"]   = importDirectory;
                    inParams["ImportSettingData"] = importSettingData.GetText(TextFormat.CimDtd20);

                    using (ManagementBaseObject outParams = virtualSystemService.InvokeMethod("ImportVirtualSystemEx", inParams, null))
                    {
                        if (outParams == null)
                        {
                            throw new ArgumentException("WMI call returned null!");
                        }
                        uint ret = (UInt32)outParams["ReturnValue"];
                        if (ret == ReturnCode.Started)
                        {
                            if (!Utility.JobCompleted(outParams, scope))
                            {
                                throw new NotSupportedException("Failed to Import VM");
                            }
                        }
                        else if (ret != ReturnCode.Completed)
                        {
                            throw new NotSupportedException(
                                      string.Format(CultureInfo.InvariantCulture, "Import virtual system failed with error:{0}", ret));
                        }
                    }
                }
            }
        }
Пример #12
0
        public static void Run()
        {
            // Create event query to be notified within 1 second of
            // a new process being created
            WqlEventQuery query =
                new WqlEventQuery("__InstanceCreationEvent",
                                  new TimeSpan(0, 0, 1),
                                  "TargetInstance isa \"Win32_Process\"");

            // Initialize an event watcher and subscribe to events
            // that match this query
            ManagementEventWatcher watcher =
                new ManagementEventWatcher(query);

            // times out watcher.WaitForNextEvent in 5 seconds
            watcher.Options.Timeout = new TimeSpan(0, 0, 5);

            // Block until the next event occurs
            // Note: this can be done in a loop if waiting for
            //        more than one occurrence
            Console.WriteLine(
                "Open an application (notepad.exe) to trigger an event.");
            ManagementBaseObject e = watcher.WaitForNextEvent();

            log.Debug(e.GetText(TextFormat.Mof));
            ManagementBaseObject target = (ManagementBaseObject)e["TargetInstance"];
            Object targetName           = target["Name"];
            Object targetPath           = target["ExecutablePath"];

            //Display information from the event
            log.Info(
                "Process {0} has been created, path is: " + targetName + ", " + targetPath);

            //Cancel the subscription
            watcher.Stop();
        }
Пример #13
0
        private bool EnterDomain()
        {
            // Invoke WMI to join the domain
            using (ManagementObject wmiObject = new ManagementObject(new ManagementPath("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")))
            {
                try
                {
                    // Obtain in-parameters for the method
                    ManagementBaseObject inParams = wmiObject.GetMethodParameters("JoinDomainOrWorkgroup");

                    inParams["Name"]         = _long_name;
                    inParams["Password"]     = _admin_password;
                    inParams["UserName"]     = fullAdminUsername;
                    inParams["FJoinOptions"] = 3; // Magic number: 3 = join to domain and create computer account

                    // Execute the method and obtain the return values.
                    ManagementBaseObject outParams = wmiObject.InvokeMethod("JoinDomainOrWorkgroup", inParams, null);

                    if (int.TryParse(outParams["ReturnValue"].ToString(), out _connect_to_domain_result))
                    {
                        return(_connect_to_domain_result == 0);
                    }
                    else
                    {
                        MessageBox.Show(outParams.GetText(TextFormat.Mof));
                        _connect_to_domain_result = 4;
                        return(false);
                    }
                }
                catch (ManagementException e)
                {
                    _connect_to_domain_result = 4;
                    return(false);
                }
            }
        }
        public static Int32 RunCommand(String command, String server, String remoteWorkingDirectory, String runAsDomain, String runAsUser, String runAsPassword, long timeoutMills, bool killProcessOnTimeout, TimeoutAction actionOnTimeout, Action <string, string> callback, string callbackLabel, bool isDryRun)
        {
            if (config.Default.DebugMode)
            {
                callback(callbackLabel, "DEBUG >> Inside RunCommand");
            }

            Int32  exitStatus = 0;
            String rwd        = config.Default.DefaultRemoteWorkingDirectory;

            if (string.IsNullOrWhiteSpace(rwd))
            {
                rwd = @"C:\Temp";
            }
            String rwdUnc = Utils.GetServerLongPath(server, rwd);
            String rwdWin = Utils.GetServerLongPathWindows(server, rwd);

            if (callback != null)
            {
                // Blank Out Any Plain Text Passwords
                string myCmd = command;
                if (command.ToLower().Contains("winrs "))
                {
                    myCmd = Regex.Replace(myCmd, @"\s-p:[^\s\\]*", @" -p:********");
                }

                if (command.ToLower().Contains("pscp ") || command.ToLower().Contains("plink "))
                {
                    myCmd = Regex.Replace(myCmd, @"\s-pw [^\s\\]*", @" -pw ********");
                }

                callback(callbackLabel, "Starting Command : " + myCmd);
            }

            if (!isDryRun)
            {
                try
                {
                    if (config.Default.DebugMode)
                    {
                        callback(callbackLabel, "DEBUG >> Setting / Creating Working Directory");
                    }

                    // Create the Remote Working Directory Using Defaults If None Is Passed In
                    if (remoteWorkingDirectory == null)
                    {
                        Utils.CreateDirectory(rwdUnc);
                    }
                    else
                    {
                        rwd    = remoteWorkingDirectory;
                        rwdUnc = Utils.GetServerLongPath(server, remoteWorkingDirectory);
                        rwdWin = Utils.GetServerLongPathWindows(server, remoteWorkingDirectory);
                    }

                    // Create the process
                    using (ManagementClass process = new ManagementClass("Win32_Process"))
                    {
                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Getting Management Scope");
                        }

                        ManagementScope scope = GetManagementScope(server, runAsDomain, runAsUser, runAsPassword);
                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Setting Process Management Scope");
                        }

                        process.Scope = scope;

                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Getting Process Method Parameters");
                        }

                        ManagementBaseObject inParams = process.GetMethodParameters("Create");

                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Creating Random Logfile Name");
                        }

                        String stdOutErrFile = System.IO.Path.GetRandomFileName();
                        stdOutErrFile = stdOutErrFile.Replace(".", "") + ".log";

                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Setting Process Method Parameters");
                        }

                        inParams["CurrentDirectory"] = rwd;
                        inParams["CommandLine"]      = @"cmd.exe /c " + command + @" 1> " + stdOutErrFile + @" 2>&1";

                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Calling InvokeMethod");
                        }

                        ManagementBaseObject mbo = process.InvokeMethod("Create", inParams, null);

                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Called InvokeMethod, Checking ReturnValue");
                        }

                        UInt32 exitCode  = (uint)mbo["ReturnValue"];
                        UInt32 processId = 0;

                        if (config.Default.DebugMode)
                        {
                            callback(callbackLabel, "DEBUG >> Return Value = [" + exitCode + "]");
                        }


                        if (exitCode == 0)
                        {
                            processId = (uint)mbo["ProcessId"];

                            if (config.Default.DebugMode)
                            {
                                callback(callbackLabel, "DEBUG >> Got ProcessId [" + processId + "]");
                            }

                            String uncOutFile    = rwdUnc + @"\" + stdOutErrFile;
                            String winUncOutFile = rwdWin + @"\" + stdOutErrFile;
                            if (server == null || "localhost".Equals(server.ToLower()) || "127.0.0.1".Equals(server.ToLower()))
                            {
                                uncOutFile    = rwd + @"\" + stdOutErrFile;
                                winUncOutFile = rwd + @"\" + stdOutErrFile;
                            }

                            // Start Tailing Output Log
                            if (config.Default.DebugMode)
                            {
                                callback(callbackLabel, "DEBUG >> Starting LogTrailer On File [" + winUncOutFile + "]");
                            }
                            LogTailer tailer = new LogTailer(winUncOutFile, callback, callbackLabel);
                            tailer.Start();

                            // Wait For Process To Finish or Timeout To Be Reached
                            ManagementEventWatcher w = new ManagementEventWatcher(scope, new WqlEventQuery("select * from Win32_ProcessStopTrace where ProcessId=" + processId));
                            if (timeoutMills > 0)
                            {
                                w.Options.Timeout = new TimeSpan(0, 0, 0, 0, (int)timeoutMills);
                            }
                            try
                            {
                                ManagementBaseObject mboEvent = w.WaitForNextEvent();
                                UInt32 uExitStatus            = (UInt32)mboEvent.Properties["ExitStatus"].Value;
                                exitStatus = unchecked ((int)uExitStatus);
                            }
                            catch (ManagementException ex)
                            {
                                if (ex.Message.Contains("Timed out"))
                                {
                                    StringBuilder rc             = new StringBuilder();
                                    String        processName    = @"cmd.exe";
                                    String        timeoutMessage = "TIMEOUT : Process [" + processName + "] With Id [" + processId + "] Failed To Stop In [" + timeoutMills + "] Milliseconds.";
                                    if (killProcessOnTimeout)
                                    {
                                        String      queryStr = String.Format("SELECT * FROM Win32_Process Where Name = '{0}' AND ProcessId = '{1}'", processName, processId);
                                        ObjectQuery Query    = new ObjectQuery(queryStr);
                                        ManagementObjectSearcher Searcher = new ManagementObjectSearcher(scope, Query);

                                        foreach (ManagementObject thisProcess in Searcher.Get())
                                        {
                                            rc.Append(KillProcess(scope, thisProcess));
                                        }

                                        using (StringReader procStr = new StringReader(rc.ToString()))
                                        {
                                            String procLine;
                                            while ((procLine = procStr.ReadLine()) != null)
                                            {
                                                if (callback != null)
                                                {
                                                    callback(callbackLabel, procLine);
                                                }
                                                else
                                                {
                                                    Console.WriteLine(procLine);
                                                }
                                            }
                                        }

                                        timeoutMessage = "TIMEOUT : Process [" + processName + "] With Id [" + processId + "] Failed To Stop In [" + timeoutMills + "] Milliseconds And Was Remotely Termintated.";
                                    }
                                    tailer.Stop(60, true);
                                    throw new Exception(timeoutMessage);
                                }
                                else
                                {
                                    tailer.Stop(60, true);
                                    throw ex;
                                }
                            }

                            // Process Completed.  Give up to 10 minutes for remote execution logs to be processed.
                            tailer.Stop(600, true);
                        }
                        else
                        {
                            if (callback != null)
                            {
                                callback(callbackLabel, "Return Value : " + exitCode);
                                callback(callbackLabel, mbo.GetText(TextFormat.Mof));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (callback != null)
                    {
                        String errorMsg = e.Message;

                        if (errorMsg.StartsWith("TIMEOUT"))
                        {
                            callback(callbackLabel, e.Message);
                        }
                        else
                        {
                            callback(callbackLabel, "Error Occured In WMIUtils.RunCommand : ");
                            callback(callbackLabel, e.Message);
                            callback(callbackLabel, e.StackTrace);
                            throw e;
                        }
                    }

                    if (actionOnTimeout == TimeoutAction.Error)
                    {
                        throw e;
                    }
                }
            }
            else
            {
                callback?.Invoke(callbackLabel, "Dry Run Flag Set.  Execution Skipped");
            }

            if (callback != null)
            {
                callback(callbackLabel, "Command Completed.  Exit Code = " + exitStatus);
            }

            return(exitStatus);
        }
Пример #15
0
 public string GetText(TextFormat format)
 {
     return(_wrapperObject.GetText(format));
 }
Пример #16
0
        public static ExecuteResult RunCommand(String command, String args, String server, String remoteWorkingDirectory, long timeoutMills, StatusType timeoutStatus = StatusType.Failed, bool killProcessOnTimeout = true, Action <string, string> callback = null, string callbackLabel = null, bool dryRun = false, bool returnStdout = true)
        {
            ExecuteResult result = new ExecuteResult();

            if (callback == null)
            {
                callback = LogTailer.ConsoleWriter;
            }

            Int32  exitStatus = 0;
            String rwd        = remoteWorkingDirectory;

            if (string.IsNullOrWhiteSpace(rwd))
            {
                rwd = @"C:\Temp";
            }

            String cmd = command;

            if (!String.IsNullOrWhiteSpace(args))
            {
                cmd = command + " " + args;
            }

            callback?.Invoke(callbackLabel, "Starting Command : " + cmd);

            if (!dryRun)
            {
                try
                {
                    // Create the process
                    using (ManagementClass process = new ManagementClass("Win32_Process"))
                    {
                        ManagementScope scope = GetManagementScope(server);
                        process.Scope = scope;

                        ManagementBaseObject inParams = process.GetMethodParameters("Create");

                        String stdOutErrFile = System.IO.Path.GetRandomFileName();
                        stdOutErrFile = stdOutErrFile.Replace(".", "") + ".log";

                        inParams["CurrentDirectory"] = rwd;
                        inParams["CommandLine"]      = @"cmd.exe /c " + cmd + @" 1> " + stdOutErrFile + @" 2>&1";

                        ManagementBaseObject mbo = process.InvokeMethod("Create", inParams, null);

                        UInt32 exitCode  = (uint)mbo["ReturnValue"];
                        UInt32 processId = 0;


                        if (exitCode == 0)
                        {
                            processId = (uint)mbo["ProcessId"];

                            // Start Tailing Output Log
                            LogTailer tailer = new LogTailer(server, Path.Combine(remoteWorkingDirectory, stdOutErrFile), callback, callbackLabel, 1000, returnStdout);
                            tailer.Start();

                            // Wait For Process To Finish or Timeout To Be Reached
                            ManagementEventWatcher w = new ManagementEventWatcher(scope, new WqlEventQuery("select * from Win32_ProcessStopTrace where ProcessId=" + processId));
                            if (timeoutMills > 0)
                            {
                                w.Options.Timeout = new TimeSpan(0, 0, 0, 0, (int)timeoutMills);
                            }
                            try
                            {
                                ManagementBaseObject mboEvent = w.WaitForNextEvent();
                                UInt32 uExitStatus            = (UInt32)mboEvent.Properties["ExitStatus"].Value;
                                exitStatus = unchecked ((int)uExitStatus);
                            }
                            catch (ManagementException ex)
                            {
                                if (ex.Message.Contains("Timed out"))
                                {
                                    StringBuilder rc             = new StringBuilder();
                                    String        processName    = @"cmd.exe";
                                    String        timeoutMessage = "TIMEOUT : Process [" + processName + "] With Id [" + processId + "] Failed To Complete In [" + timeoutMills + "] Milliseconds.";
                                    if (killProcessOnTimeout)
                                    {
                                        String      queryStr = String.Format("SELECT * FROM Win32_Process Where Name = '{0}' AND ProcessId = '{1}'", processName, processId);
                                        ObjectQuery Query    = new ObjectQuery(queryStr);
                                        ManagementObjectSearcher Searcher = new ManagementObjectSearcher(scope, Query);

                                        foreach (ManagementObject thisProcess in Searcher.Get())
                                        {
                                            rc.Append(KillProcess(scope, thisProcess));
                                        }

                                        using (StringReader procStr = new StringReader(rc.ToString()))
                                        {
                                            String procLine;
                                            while ((procLine = procStr.ReadLine()) != null)
                                            {
                                                callback?.Invoke(callbackLabel, procLine);
                                            }
                                        }

                                        timeoutMessage = "TIMEOUT : Process [" + processName + "] With Id [" + processId + "] Failed To Complete In [" + timeoutMills + "] Milliseconds And Was Remotely Termintated.";
                                    }
                                    tailer.Stop(60, true);
                                    result.ExitData = tailer.Contents;

                                    throw new Exception(timeoutMessage);
                                }
                                else
                                {
                                    tailer.Stop(60, true);
                                    result.ExitData = tailer.Contents;
                                    throw ex;
                                }
                            }

                            tailer.Stop(300, true);
                            result.ExitData = tailer.Contents;
                        }
                        else
                        {
                            callback?.Invoke(callbackLabel, "Return Value : " + exitCode);
                            callback?.Invoke(callbackLabel, mbo.GetText(TextFormat.Mof));
                        }
                    }   // End Using
                }
                catch (Exception e)
                {
                    String errorMsg = e.Message;

                    if (errorMsg.StartsWith("TIMEOUT"))
                    {
                        callback?.Invoke(callbackLabel, e.Message);
                        result.Status = timeoutStatus;
                        callback?.Invoke(callbackLabel, "TIMEOUT : Returning Timeout Stauts [" + result.Status + "].");
                    }
                    else
                    {
                        callback?.Invoke(callbackLabel, "Error Occured In WMIUtils.RunCommand : ");
                        callback?.Invoke(callbackLabel, e.Message);
                        callback?.Invoke(callbackLabel, e.StackTrace);
                        throw e;
                    }
                }
            }
            else
            {
                callback?.Invoke(callbackLabel, "Dry Run Flag Set.  Execution Skipped");
            }

            result.ExitCode = exitStatus;
            result.Message  = "Exit Code = " + exitStatus;
            callback?.Invoke(callbackLabel, result.Message);

            return(result);
        }