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(); }
public static void WatchDrives(Action handler) { using (var watcher = new ManagementEventWatcher()) { WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); watcher.EventArrived += (e, sender) => handler(); watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); } }
static void Main(string[] args) { string dirToWatch = "C:\\\\SSIS\\\\Files\\\\Tyson\\\\BI\\\\Incoming\\\\"; string dirDest = "\\\\\\\\whqwssissb02\\\\SSIS\\\\Files\\\\Tyson\\\\BI\\\\Incoming\\\\"; string dirLog = "C:\\\\SSIS\\\\Files\\\\Tyson\\\\BI\\\\"; string logFileName = "SSISIncomingDirectoryWatcher.log"; string drive = Regex.Replace(dirToWatch, @"(.*:).*", "$1"); string path = Regex.Replace(dirToWatch, @".*:(.*)", "$1"); FileInfo file; TextWriter tw = File.CreateText(dirLog + logFileName); // Create a query to be notified within 1 second of a file creation WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"CIM_DataFile\" AND " + "TargetInstance.Drive=\"" + drive + "\" AND " + "TargetInstance.Path=\"" + path + "\""); // Initialize an event watcher and subscribe to events that match this query ManagementEventWatcher watcher = new ManagementEventWatcher(query); // Block until the next event occurs ManagementBaseObject e = watcher.WaitForNextEvent(); string name = (string)((ManagementBaseObject)e["TargetInstance"])["Name"]; file = new FileInfo(name); string destPath = Path.Combine(dirDest, file.Name); file.CopyTo(destPath); tw.WriteLine("Moved [{0}] to [{1}] at {2}", name, destPath, DateTime.Now); //Console.WriteLine("Name: {0}", ((ManagementBaseObject)e["TargetInstance"])["Name"]); //Console.WriteLine("FileName: {0}", ((ManagementBaseObject)e["TargetInstance"])["FileName"]); // Run this bitch to discover what's available. //ManagementBaseObject dataFile = (ManagementBaseObject)e["TargetInstance"]; //PropertyDataCollection properties = dataFile.Properties; //foreach (PropertyData property in properties) //{ // Console.WriteLine("{0}: {1}", property.Name, property.Value); //} watcher.Stop(); tw.Close(); Console.WriteLine("Press any key to exit..."); Console.ReadLine(); }
public static void Run() { WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\""); ManagementEventWatcher watcher = new ManagementEventWatcher(); watcher.Query = query; watcher.Options.Timeout = new TimeSpan(0,0,5); Console.WriteLine("Open application (motepad.exe) to trigger an event."); ManagementBaseObject e = watcher.WaitForNextEvent(); Console.WriteLine("Process {0} has been created, path is: {1}", ((ManagementBaseObject)e["TargetInstance"])["Name"], ((ManagementBaseObject)e["TargetInstance"])["ExecutablePath"]); watcher.Stop(); }
static void Main(string[] args) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"); ManagementObjectCollection queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { 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"]); } //----------------------------------------------------------------------------------------- //Process creation event (waiting for) WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\""); ManagementEventWatcher watcher = new ManagementEventWatcher(query); ManagementBaseObject e = watcher.WaitForNextEvent(); Console.WriteLine("Process {0} has been created, path is: {1}", ((ManagementBaseObject)e["TargetInstance"])["Name"], ((ManagementBaseObject)e["TargetINstance"])["ExecutablePath"]); watcher.Stop(); //----------------------------------------------------------------------------------------- //Responding to WMI Events with an Event Handler ManagementEventWatcher mew = null; EventReceiver receiver = new EventReceiver(); mew = GetWatcher(new EventArrivedEventHandler(receiver.OnEventArrived)); mew.Start(); Console.ReadKey(); mew.Stop(); }
public void ExecuteRemoteProcess(string command) { Wmi cimv2 = new Wmi(ServerNameSettings, "root\\cimv2"); ManagementClass objProcess = cimv2.GetWmiClass("Win32_Process"); // run process object[] methodArgs = { command, null, null, 0 }; objProcess.InvokeMethod("Create", methodArgs); // process ID int processId = Convert.ToInt32(methodArgs[3]); // wait until finished // Create event query to be notified within 1 second of // a change in a service WqlEventQuery query = new WqlEventQuery("__InstanceDeletionEvent", 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(cimv2.GetScope(), query); // times out watcher.WaitForNextEvent in 20 seconds watcher.Options.Timeout = new TimeSpan(0, 0, 20); // Block until the next event occurs // Note: this can be done in a loop if waiting for // more than one occurrence while (true) { ManagementBaseObject e = null; try { // wait untill next process finish e = watcher.WaitForNextEvent(); } catch { // nothing has been finished in timeout period return; // exit } // check process id int pid = Convert.ToInt32(((ManagementBaseObject)e["TargetInstance"])["ProcessID"]); if (pid == processId) { //Cancel the subscription watcher.Stop(); // exit return; } } }
/// <summary>Runs some command.</summary> /// <param name="command">The command to run.</param> /// <param name="wmiScope"> The ManagementScope object to connect to. (default=none).</param> /// <param name="wait">Command's timeout expiration.</param> /// <remarks>IMPORTANT: 'domain/login/password' must have correct priviledges on the CIMV2 path ('Access denied' => see http://msdn.microsoft.com/en-us/library/windows/desktop/aa393613%28v=vs.85%29.aspx )</remarks> /// TODO: ?? Replace 'wait' parameter with some cancel callback ?? public static int Run(string command, ManagementScope wmiScope, double wait = double.PositiveInfinity) { // We let internal functions check and make defaults if (double.IsNaN(wait) || (wait < 0.0)) { throw new ArgumentException("wait range is 1-9999"); } // Process survey var processId = new[] { (uint)0 }; var exitCode = 0; var arguments = ((command ?? "")).Trim(); var watcher = (ManagementEventWatcher)null; var scope = (ManagementScope)null; // Note for the following code by mmcpherson 2014/02/13: // Originally I used the asynchronous implementation of WMI. Unfortunately using asynchronous would cause WMI access denied errors // if the source and target computers were not in the same domain!!! I could not find a simple solution for this. // // I had to modify the solution so that it is now semi-synchronous, which is a compromise. Using this method prevents the UI // thread from freezing, and still allows for some feedback whether a remote process has started or stopped. This is reliant // on that the WMI timeout period is set to wait for long enough of a time. try { // Connecting to WMI scope var span = TimeSpan.FromSeconds(0); // TODO: ?? relate to 'wait' or check cancel ?? // Removing use of wmi scope options for my own built in RemoteConnect //scope = connectToWmiScope(machine, domain, username, password, securePassword, span); scope = wmiScope; // Begin process stop watcher Func<uint> getProcessId = () => processId[0]; Action<int> setExitCode = (code) => exitCode = code; // Create the process processId[0] = createProcess(scope, arguments); // Create event query to be notified within 1 second of // a change in a service WqlEventQuery query = new WqlEventQuery("SELECT * From WIN32_ProcessStopTrace WHERE ProcessID=" + getProcessId()); // Initialize an event watcher and subscribe to events // that match this query watcher = new ManagementEventWatcher(scope, query); // times out watcher.WaitForNextEvent in 5 seconds watcher.Options.Timeout = new TimeSpan(0, 0, (int)wait); // Block until the next event occurs // Note: this can be done in a loop if waiting for // more than one occurrence ManagementBaseObject e = watcher.WaitForNextEvent(); //Cancel the subscription watcher.Stop(); return exitCode; /* * // TODO: THe following can be implemented for detecting timeouts & restarted servers to prevent issues with timeout exceptions * http://stackoverflow.com/questions/12159989/asynchronous-wmi-event-handling-in-net ManagementEventWatcher w = new ManagementEventWatcher(managementScope, new WqlEventQuery("select * from Win32_ProcessStopTrace where ProcessId=" + ProcessId)); w.Options.Timeout = new TimeSpan(0, 0, 0, 0, 1); DateTime start = DateTime.Now; while (Status == StatusNotStarted) //default status(just strings) { try { var ev = w.WaitForNextEvent(); ReturnCode = (uint)ev.Properties["ExitStatus"].Value; Status = (ReturnCode == 0) ? StatusOk : StatusFailed; } catch (ManagementException ex) { if (!ex.Message.Contains("Timed out")) throw ex; try { Ping p = new Ping(); PingReply reply = p.Send(MachineIP); if (reply.Status != IPStatus.Success) Status = StatusFailed; else { DateTime end = DateTime.Now; TimeSpan duration = end - start; if (duration.TotalMilliseconds > Timeout) { Status = StatusFailed; } } } */ } catch (Exception ex) { var msg = dumpRunArguments(command, wait); msg = string.Format("Command execution failed:\n{0}", msg); if (Log.WriteLog != null) { Log.WriteLog("ERROR: " + msg); } if (ex is TimeoutException) { if (Log.WriteLog != null) { Log.WriteLog("ERROR: Exception is timeout, trying to kill process: "+ ex.Message); } if ((scope != null) && (processId[0] != 0)) { bool found; tryKillProcess(scope, processId[0], out found); } } throw new Exception(msg, ex); } finally { if (watcher != null) { watcher.Stop(); watcher.Dispose(); } } }
// The main entry point for the application. static void Main(string[] args) { // Get the name of the computer on // which this program runs. // Note. The monitored application must also run // on this computer. string machine = Environment.MachineName; // Define the Common Information Model (CIM) path // for WIM monitoring. string path = String.Format("\\\\{0}\\root\\aspnet", machine); // Create a managed object watcher as // defined in System.Management. string query = "select * from BaseEvent"; ManagementEventWatcher watcher = new ManagementEventWatcher(query); // Set the watcher options. TimeSpan timeInterval = new TimeSpan(0, 1, 30); watcher.Options = new EventWatcherOptions(null, timeInterval, 1); // Set the scope of the WMI events to // watch to be ASP.NET applications. watcher.Scope = new ManagementScope(new ManagementPath(path)); // Set the console background. Console.BackgroundColor = ConsoleColor.Blue; // Set foreground color. Console.ForegroundColor = ConsoleColor.Yellow; // Clear the console. Console.Clear(); // Loop indefinitely to catch the events. Console.WriteLine( "Listener started. Enter CntlC to terminate"); while (true) { try { // Capture the WMI event related to // the Web event. ManagementBaseObject ev = watcher.WaitForNextEvent(); // Display the Web event information. DisplayEventInformation(ev); // Prompt the user. Console.Beep(); } catch (Exception e) { Console.WriteLine("Error: {0}", e); break; } } }