public static ManagementObject[] getVhdSettings(ManagementObject virtualMachine, ManagementScope Scope) { using (ManagementObject mObject = getSettingData(wmiClass.Msvm_VirtualSystemSettingData.ToString(), wmiClass.Msvm_SettingsDefineState.ToString(), virtualMachine, Scope)) { return getVHDSettings(mObject); } }
/// <summary> /// The start detection. /// </summary> /// <param name="action"> /// The detection Action. /// </param> public void StartDetection(Action action) { ThreadPool.QueueUserWorkItem( delegate { this.detectionAction = action; var options = new ConnectionOptions { EnablePrivileges = true }; var scope = new ManagementScope(@"root\CIMV2", options); try { var query = new WqlEventQuery { EventClassName = "__InstanceModificationEvent", WithinInterval = TimeSpan.FromSeconds(1), Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5" // DriveType - 5: CDROM }; this.watcher = new ManagementEventWatcher(scope, query); this.watcher.EventArrived += this.WatcherEventArrived; this.watcher.Start(); } catch (Exception e) { Console.WriteLine(e.Message); } }); }
//private char NULL_VALUE = char(0); public static ProcessReturnCode Run(string machineName, string commandLine, string args, string currentDirectory) { var connOptions = new ConnectionOptions { EnablePrivileges = true }; var scope = new ManagementScope(@"\\{0}\root\cimv2".FormatWith(machineName), connOptions); scope.Connect(); var managementPath = new ManagementPath(CLASSNAME); using (var processClass = new ManagementClass(scope, managementPath, new ObjectGetOptions())) { var inParams = processClass.GetMethodParameters("Create"); commandLine = System.IO.Path.Combine(currentDirectory, commandLine); inParams["CommandLine"] = "{0} {1}".FormatWith(commandLine, args); var outParams = processClass.InvokeMethod("Create", inParams, null); var rtn = Convert.ToUInt32(outParams["returnValue"]); var pid = Convert.ToUInt32(outParams["processId"]); if (pid != 0) { WaitForPidToDie(machineName, pid); } return (ProcessReturnCode)rtn; } }
public static string ShowUserSID(string username) { // local scope string[] unames = username.Split("\\".ToCharArray(),2); string d = ""; string n = ""; d = unames[0]; if (unames.Length < 2) { n = unames[0]; d = "US_IBS"; } else n = unames[1]; ConnectionOptions co = new ConnectionOptions(); //co.Username = username; ManagementScope msc = new ManagementScope ("\\root\\cimv2",co); string queryString = "SELECT * FROM Win32_UserAccount where LocalAccount = false AND SIDType = 1 AND Domain = '" + d+ "' AND Name = '" + n + "'"; //System.Windows.Forms.MessageBox.Show(queryString); SelectQuery q = new SelectQuery (queryString); query = new ManagementObjectSearcher(msc, q); queryCollection = query.Get(); string res=String.Empty; foreach( ManagementObject mo in queryCollection ) { // there should be only one here! res+= mo["SID"].ToString(); //res+= mo["Name"]+"\n"; } return res; }
protected virtual void GetOperatingSystemInfo(string Name, string UserName, string Password) { if (string.IsNullOrEmpty(Name)) throw new ArgumentNullException("Name"); ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempNetworkAdapter in Collection) { if (TempNetworkAdapter.Properties["LastBootUpTime"].Value != null) { LastBootUpTime = ManagementDateTimeConverter.ToDateTime(TempNetworkAdapter.Properties["LastBootUpTime"].Value.ToString()); } } } } }
/// <summary> /// Tries to connect to the host specified. The connection is used WMI. /// </summary> /// <param name="target">Host to Connect</param> public void Connect(TargetInfo target) { try { Credentials credentials = target.IsLocalTarget() ? null : target.credentials; ConnectionOptions options = this.GetConnectionOptions(credentials); this.ConnectionScope = this.GetManagementScope(options, target.GetAddress()); } catch (UnauthorizedAccessException unauthorizedAccessException) { string errorMessage = string.Format(INVALID_CREDENTIALS_ERROR_MESSAGE, target.GetAddress(), target.credentials.GetDomain(), target.credentials.GetUserName()); throw new InvalidCredentialsException(target.credentials, errorMessage, unauthorizedAccessException); } catch (COMException comException) { string errorMessage = string.Format(PROVIDER_CONNECTING_ERROR_MESSAGE, target.GetAddress(), comException.Message); throw new CannotConnectToHostException(target, errorMessage, comException); } catch (Exception ex) { string errorMessage = string.Format(PROVIDER_CONNECTING_ERROR_MESSAGE, target.GetAddress(), ex.Message); throw new ProbeException(errorMessage, ex); } }
public void AddARecord(string hostName, string zone, string iPAddress, string dnsServerName) { /*ConnectionOptions connOptions = new ConnectionOptions(); connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; connOptions.Username = "******"; connOptions.Password = "******"; */ ManagementScope scope = new ManagementScope(@"\\" + dnsServerName + "\\root\\MicrosoftDNS"); //,connOptions); scope.Connect(); ManagementClass wmiClass = new ManagementClass(scope, new ManagementPath("MicrosoftDNS_AType"), null); ManagementBaseObject inParams = wmiClass.GetMethodParameters("CreateInstanceFromPropertyData"); inParams["DnsServerName"] = dnsServerName; inParams["ContainerName"] = zone; inParams["OwnerName"] = hostName + "." + zone; inParams["IPAddress"] = iPAddress; wmiClass.InvokeMethod("CreateInstanceFromPropertyData", inParams, null); }
public static ManagementScope GetScope(string ns = @"root\cimv2", string server = ".", string username = null, string password = null) { var scope = new ManagementScope() { Options = { Impersonation = ImpersonationLevel.Impersonate, Authentication = AuthenticationLevel.PacketPrivacy, EnablePrivileges = true }, Path = new ManagementPath() { NamespacePath = ns, Server = server } }; if (!string.IsNullOrWhiteSpace(username)) scope.Options.Username = username; if (!string.IsNullOrWhiteSpace(password)) scope.Options.Password = password; return scope; }
public static string getUserName() { try { var x = ""; var connectionOptions = new ConnectionOptions(); var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions); var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem"); using (var searcher = new ManagementObjectSearcher(scope, query)) { var builder = new System.Text.StringBuilder(); builder.Append(x); foreach (var row in searcher.Get()) { builder.Append((row["UserName"].ToString() + " ")); } x = builder.ToString(); return x; } } catch (Exception ex) { return ""; } }
public static List<EntOS> GetOSDetails(ManagementScope scope) { _logger.Info("Collecting OS details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntOS> lstOS = new List<EntOS>(); try { query = new ObjectQuery("Select * from Win32_OperatingSystem"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstOS.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstOS.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception in OS collection " + e.Message); } finally { searcher.Dispose(); } return lstOS; }
AttachVirtualHardDisk( string ServerName, string VirtualHardDiskPath, string AssignDriveLetters, string ReadOnly) { ManagementScope scope = new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2"); using (ManagementObject imageManagementService = StorageUtilities.GetImageManagementService(scope)) { using (ManagementBaseObject inParams = imageManagementService.GetMethodParameters("AttachVirtualHardDisk")) { inParams["Path"] = VirtualHardDiskPath; inParams["AssignDriveLetter"] = AssignDriveLetters; inParams["ReadOnly"] = ReadOnly; using (ManagementBaseObject outParams = imageManagementService.InvokeMethod( "AttachVirtualHardDisk", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); } } } }
protected override void OnCommitted(IDictionary savedState) { base.OnCommitted (savedState); // Setting the "Allow Interact with Desktop" option for this service. ConnectionOptions connOpt = new ConnectionOptions(); connOpt.Impersonation = ImpersonationLevel.Impersonate; ManagementScope mgmtScope = new ManagementScope(@"root\CIMv2", connOpt); mgmtScope.Connect(); ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ReflectorMgr.ReflectorServiceName + "'"); ManagementBaseObject inParam = wmiService.GetMethodParameters("Change"); inParam["DesktopInteract"] = true; ManagementBaseObject outParam = wmiService.InvokeMethod("Change", inParam, null); #region Start the reflector service immediately try { ServiceController sc = new ServiceController("ConferenceXP Reflector Service"); sc.Start(); } catch (Exception ex) { // Don't except - that would cause a rollback. Instead, just tell the user. RtlAwareMessageBox.Show(null, string.Format(CultureInfo.CurrentCulture, Strings.ServiceStartFailureText, ex.ToString()), Strings.ServiceStartFailureTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0); } #endregion }
public WmiWrapper(ManagementPath path) { _scope = new ManagementScope(path) { Options = { Impersonation = ImpersonationLevel.Impersonate } }; }
GetVMGeneration( string serverName, string vmName) { ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null); using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope)) using (ManagementObject vmSettings = WmiUtilities.GetVirtualMachineSettings(vm)) { string virtualSystemSubType = (string)vmSettings["VirtualSystemSubType"]; if (string.Equals(virtualSystemSubType, "Microsoft:Hyper-V:SubType:1", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("VM {0} on server {1} is generation 1", vmName, serverName); } else if (string.Equals(virtualSystemSubType, "Microsoft:Hyper-V:SubType:2", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("VM {0} on server {1} is generation 2", vmName, serverName); } else { Console.WriteLine("VM {0} on server {1} is an unknown generation", vmName, serverName); } } }
public static List<EntDisk>GetDiskDetails(ManagementScope scope) { _logger.Info("Collecting disk details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntDisk> lstDisk = new List<EntDisk>(); try { query = new ObjectQuery("Select * from Win32_DiskDrive"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstDisk.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstDisk.Add(FillDetails(obj)); obj.Dispose(); } } catch (Exception e) { _logger.Error("Exception is disk collection " + e.Message); } finally { searcher.Dispose(); } return lstDisk; }
private string GetBatteryPercent() { try { var scope = new ManagementScope(); SelectQuery query = new SelectQuery("Select EstimatedChargeRemaining From Win32_Battery"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) { using (ManagementObjectCollection objectCollection = searcher.Get()) { foreach (ManagementObject mObj in objectCollection) //this nugget has a lot of info see here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa394074%28v=vs.85%29.aspx { PropertyData pData = mObj.Properties["EstimatedChargeRemaining"]; var val = pData.Value; if ((ushort) val > (ushort) 100) { return "100"; } else { return val.ToString().Replace("%",""); //strip % in case it duplicates } } } } return "Unk"; } catch (Exception e) { Debug.WriteLine(e); return "Unk"; } }
static IEnumerable<byte[]> GetManagementObjects() { var options = new EnumerationOptions {Rewindable = false, ReturnImmediately = true}; var scope = new ManagementScope(ManagementPath.DefaultPath); var query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter"); var searcher = new ManagementObjectSearcher(scope, query, options); ManagementObjectCollection collection = searcher.Get(); foreach (ManagementObject obj in collection) { byte[] bytes; try { PropertyData propertyData = obj.Properties["MACAddress"]; string propertyValue = propertyData.Value.ToString(); bytes = propertyValue.Split(':') .Select(x => byte.Parse(x, NumberStyles.HexNumber)) .ToArray(); } catch (Exception) { continue; } if (bytes.Length == 6) yield return bytes; } }
public static List<EntHotfixes> GetHotfixDetails(ManagementScope scope) { _logger.Info("Collecting hotfix for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntHotfixes> lstHotfix = new List<EntHotfixes>(); try { query = new ObjectQuery("Select * from Win32_QuickFixEngineering"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstHotfix.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstHotfix.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception is hotfix collection " + e.Message); } finally { searcher.Dispose(); } return lstHotfix; }
public static List<Object[]> checkAntiVirus() { List<Object[]> av = new List<Object[]>(); ConnectionOptions _connectionOptions = new ConnectionOptions(); _connectionOptions.EnablePrivileges = true; _connectionOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope _managementScope = new ManagementScope(string.Format("\\\\{0}\\root\\SecurityCenter2", "localhost"), _connectionOptions); _managementScope.Connect(); ObjectQuery _objectQuery = new ObjectQuery("SELECT * FROM AntivirusProduct"); ManagementObjectSearcher _managementObjectSearcher = new ManagementObjectSearcher(_managementScope, _objectQuery); ManagementObjectCollection _managementObjectCollection = _managementObjectSearcher.Get(); if (_managementObjectCollection.Count > 0) { Boolean updated = false; foreach (ManagementObject item in _managementObjectCollection) { updated = (item["productState"].ToString() == "266240" || item["productState"].ToString() == "262144"); av.Add(new Object[] { item["displayName"].ToString(), updated }); } } return av; }
/// <summary> /// Gets a list of files on the machine with a specific extension /// </summary> /// <param name="Computer">Computer to search</param> /// <param name="UserName">User name (if not local)</param> /// <param name="Password">Password (if not local)</param> /// <param name="Extension">File extension to look for</param> /// <returns>List of files that are found to have the specified extension</returns> public static IEnumerable<string> GetFilesWithExtension(string Computer, string UserName, string Password, string Extension) { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Computer), "Computer"); Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Extension), "Extension"); List<string> Files = new List<string>(); ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM CIM_DataFile where Extension='" + Extension + "'"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempBIOS in Collection) { Files.Add(TempBIOS.Properties["Drive"].Value.ToString()+TempBIOS.Properties["Path"].Value.ToString()+TempBIOS.Properties["FileName"].Value.ToString()); } } } return Files; }
DeleteSwitch( string switchName) { ManagementScope scope = new ManagementScope(@"root\virtualization\v2"); // // Find the switch that we want to delete. // using (ManagementObject ethernetSwitch = NetworkingUtilities.FindEthernetSwitch(switchName, scope)) // // Now that we have the switch object we can delete it. // using (ManagementObject switchService = NetworkingUtilities.GetEthernetSwitchManagementService(scope)) using (ManagementBaseObject inParams = switchService.GetMethodParameters("DestroySystem")) { inParams["AffectedSystem"] = ethernetSwitch.Path.Path; using (ManagementBaseObject outParams = switchService.InvokeMethod("DestroySystem", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); } } Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "The switch '{0}' was deleted successfully.", switchName)); }
/// <summary> /// Loads the BIOS info /// </summary> /// <param name="Name">Computer name</param> /// <param name="UserName">User name</param> /// <param name="Password">Password</param> private void LoadBIOS(string Name, string UserName, string Password) { ManagementScope Scope = null; if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { ConnectionOptions Options = new ConnectionOptions(); Options.Username = UserName; Options.Password = Password; Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options); } else { Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2"); } Scope.Connect(); ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_BIOS"); using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query)) { using (ManagementObjectCollection Collection = Searcher.Get()) { foreach (ManagementObject TempBIOS in Collection) { SerialNumber = TempBIOS.Properties["Serialnumber"].Value.ToString(); } } } }
ModifyClusterMonitored( string virtualMachineName, bool onOff) { // Get management scope ManagementScope scope = new ManagementScope(@"root\virtualization\v2"); int syntheticPortCount = 0; // Get virtual system management service using (ManagementObject managementService = WmiUtilities.GetVirtualMachineManagementService(scope)) // Find the virtual machine we want to modify the synthetic ethernet ports of. using (ManagementObject virtualMachine = WmiUtilities.GetVirtualMachine(virtualMachineName, scope)) // Find the virtual system setting data using (ManagementObject virtualMachineSettings = WmiUtilities.GetVirtualMachineSettings(virtualMachine)) // Find all synthetic ethernet ports for the given virtual machine. using (ManagementObjectCollection syntheticPortSettings = virtualMachineSettings.GetRelated( "Msvm_SyntheticEthernetPortSettingData", "Msvm_VirtualSystemSettingDataComponent", null, null, null, null, false, null)) { syntheticPortCount = syntheticPortSettings.Count; try { // Modify each port setting to update the property. foreach (ManagementObject syntheticEthernetPortSetting in syntheticPortSettings) { syntheticEthernetPortSetting[PropertyNames.ClusterMonitored] = onOff; // Now apply the changes to the Hyper-V server. using (ManagementBaseObject inParams = managementService.GetMethodParameters("ModifyResourceSettings")) { inParams["ResourceSettings"] = new string[] { syntheticEthernetPortSetting.GetText(TextFormat.CimDtd20) }; using (ManagementBaseObject outParams = managementService.InvokeMethod("ModifyResourceSettings", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); } } } } finally { // Dispose of the synthetic ethernet port settings. foreach (ManagementObject syntheticEthernetPortSetting in syntheticPortSettings) { syntheticEthernetPortSetting.Dispose(); } } } Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "Successfully modified virtual machine '{0}' so that each of its {1} synthetic ethernet port(s) " + "has {2} property modified to {3}.", virtualMachineName, syntheticPortCount, PropertyNames.ClusterMonitored, onOff)); }
/// <summary> /// Gets COM port list. /// </summary> /// <returns>Enumerable list of COM ports.</returns> public static IEnumerable<ComPortItem> GetComPorts() { var result = new List<ComPortItem>(); ManagementScope connectionScope = new ManagementScope(); SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery); try { foreach (ManagementObject item in searcher.Get()) { string portName = item["DeviceID"].ToString(); string portDescription = item["DeviceID"].ToString(); // COM port with Arduino is not detected. // portDescription.Contains("Arduino") is not working. // I should find out how to get value "Arduino Uno" from "Описание устройства, предоставленное шиной" parameter. // And where is this parameter? result.Add(new ComPortItem(portName, portDescription.Contains("Arduino"))); } } catch (ManagementException) { } return result; }
ConfigureMmioGap( string vmName, uint gapSize) { ManagementScope scope = new ManagementScope(@"root\virtualization\v2"); using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope)) using (ManagementObject vssd = WmiUtilities.GetVirtualMachineSettings(vm)) using (ManagementObject vmms = WmiUtilities.GetVirtualMachineManagementService(scope)) using (ManagementBaseObject inParams = vmms.GetMethodParameters("ModifySystemSettings")) { Console.WriteLine("Configuring MMIO gap size of Virtual Machine \"{0}\" ({1}) " + "to {2} MB...", vm["ElementName"], vm["Name"], gapSize); vssd["LowMmioGapSize"] = gapSize; inParams["SystemSettings"] = vssd.GetText(TextFormat.CimDtd20); using (ManagementBaseObject outParams = vmms.InvokeMethod("ModifySystemSettings", inParams, null)) { if (WmiUtilities.ValidateOutput(outParams, scope)) { Console.WriteLine("Configuring MMIO gap size succeeded.\n"); } } } }
IsAvailable( string serverName, string vmName) { ManagementScope scope = new ManagementScope(@"\\" + serverName + @"\root\virtualization\v2", null); using (ManagementObject vm = WmiUtilities.GetVirtualMachine(vmName, scope)) { UInt16 enhancedModeState = (UInt16)vm.GetPropertyValue("EnhancedSessionModeState"); if (enhancedModeState == CimEnabledStateEnabled) { Console.WriteLine("Enhanced mode is allowed and currently available on VM {0} on server {1}", vmName, serverName); } else if (enhancedModeState == CimEnabledStateDisabled) { Console.WriteLine("Enhanced mode is not allowed on VM {0} on server {1}", vmName, serverName); } else if (enhancedModeState == CimEnabledStateEnabledButOffline) { Console.WriteLine("Enhanced mode is allowed and but not currently available on VM {0} on server {1}", vmName, serverName); } else { Console.WriteLine("Enhanced mode state on VM {0} on server {1} is {2}", vmName, serverName, enhancedModeState); } } }
internal WebSite(ManagementScope scope, string serverComment, string siteName) : base(scope) { this.ServerComment = serverComment; this.Name = siteName; this.IdentityQuery = string.Format("SELECT * FROM IISWebServer WHERE Name = '{0}'", this.Name); }
MergeVirtualHardDisk( string ServerName, string ChildPath, string ParentPath) { ManagementScope scope = new ManagementScope("\\\\" + ServerName + "\\root\\virtualization\\v2"); using (ManagementObject imageManagementService = StorageUtilities.GetImageManagementService(scope)) { using (ManagementBaseObject inParams = imageManagementService.GetMethodParameters("MergeVirtualHardDisk")) { inParams["SourcePath"] = ChildPath; inParams["DestinationPath"] = ParentPath; using (ManagementBaseObject outParams = imageManagementService.InvokeMethod( "MergeVirtualHardDisk", inParams, null)) { WmiUtilities.ValidateOutput(outParams, scope); } } } }
/// <summary> /// USB 插入和拔出监测函数。 /// 使用ManagementEventWacher来预定特定系统事件,通过WqlEventQuery设置查询对象和条件以及其他属性(比如查询的轮询间隔), /// 通过ManagementScope设置查询路径范围。 /// </summary> public void USBRemoveWacher() { ManagementEventWatcher wacher = null; WqlEventQuery query = null; ManagementScope scope = null; try { scope = new ManagementScope("root\\CIMV2"); //设置WMI路径 query = new WqlEventQuery(); //设置查询的事件类名,条件,查询间隔,也可一次在构造函数中初始化 query.EventClassName = "__InstanceDeletionEvent"; query.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"; query.WithinInterval = new TimeSpan(1000); wacher = new ManagementEventWatcher(scope, query); wacher.EventArrived += new EventArrivedEventHandler(onUSBRemoved); wacher.Start(); } catch (Exception ex) { MessageBox.Show(ex.Message); } this.Closed += (s, e) => { wacher.Stop(); wacher.Dispose(); }; }
private void AddInsertUSBHandler() { WqlEventQuery query; ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; insertUSBWatcher = null; try { query = new WqlEventQuery(); query.EventClassName = "__InstanceCreationEvent"; query.WithinInterval = new TimeSpan(0, 0, 3); query.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'"; insertUSBWatcher = new ManagementEventWatcher(scope, query); insertUSBWatcher.EventArrived += USBInserted; insertUSBWatcher.Start(); } catch(Exception e) { if (insertUSBWatcher != null) { insertUSBWatcher.Stop(); } throw e; } }
public static RegistryEventCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, System.String [] selectedProperties) { if ((mgmtScope == null)) { if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "root\\DEFAULT"; } else { mgmtScope = statMgmtScope; } } System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("RegistryEvent", condition, selectedProperties)); System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); enumOptions.EnsureLocatable = true; ObjectSearcher.Options = enumOptions; return(new RegistryEventCollection(ObjectSearcher.Get())); }
static int FetchCurrentBrightness() { byte CurrentBrightness = 0; System.Management.ManagementScope ManScope = new System.Management.ManagementScope("ROOT\\WMI"); System.Management.SelectQuery ManQuery = new System.Management.SelectQuery("WmiMonitorBrightness"); System.Management.ManagementObjectSearcher ManObjS = new System.Management.ManagementObjectSearcher(ManScope, ManQuery); System.Management.ManagementObjectCollection ManObjC = ManObjS.Get(); foreach (System.Management.ManagementObject ManObject in ManObjC) { CurrentBrightness = (byte)ManObject.GetPropertyValue("CurrentBrightness"); break; } ManObjC.Dispose(); ManObjS.Dispose(); return((int)CurrentBrightness); }
public static SendHandler2Collection GetInstances(System.Management.ManagementScope mgmtScope, string condition, System.String [] selectedProperties) { if ((mgmtScope == null)) { if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "root\\MicrosoftBizTalkServer"; } else { mgmtScope = statMgmtScope; } } System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("MSBTS_SendHandler2", condition, selectedProperties)); System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); enumOptions.EnsureLocatable = true; ObjectSearcher.Options = enumOptions; return(new SendHandler2Collection(ObjectSearcher.Get())); }
private void serviceInstaller1_AfterInstall(object sender, System.Configuration.Install.InstallEventArgs e) { ConnectionOptions coOptions = new ConnectionOptions(); coOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", coOptions); mgmtScope.Connect(); ServiceController sc = new ServiceController("CardReaderService"); ManagementObject wmiService; wmiService = new ManagementObject("Win32_Service.Name='" + sc.ServiceName + "'"); ManagementBaseObject InParam = wmiService.GetMethodParameters("Change"); InParam["DesktopInteract"] = true; ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null); }
public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { if ((mgmtScope == null)) { if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; } else { mgmtScope = statMgmtScope; } } System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SyntheticEthernetPortSettingData", condition, selectedProperties)); System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); enumOptions.EnsureLocatable = true; ObjectSearcher.Options = enumOptions; return(new SyntheticEthernetPortSettingDataCollection(ObjectSearcher.Get())); }
/// <summary> /// /// </summary> /// <param name="stateSaver"></param> public override void Install(System.Collections.IDictionary stateSaver) { this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; base.Install(stateSaver); ConnectionOptions coOptions = new ConnectionOptions(); coOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", coOptions); mgmtScope.Connect(); using (ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + MirrorService.RegisteredServiceName + "'")) { ManagementBaseObject InParam = wmiService.GetMethodParameters("Change"); InParam["DesktopInteract"] = false; wmiService.InvokeMethod("Change", InParam, null); } ConfigureRecoveryMechanism(); }
public static string[] GetCurrentActiveUsers() { List <string> users = new List <string>(); try { ConnectionOptions oConn = new ConnectionOptions(); System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn); System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select * from Win32_ComputerSystem"); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery); ManagementObjectCollection oReturnCollection = oSearcher.Get(); foreach (ManagementObject oReturn in oReturnCollection) { users.Add(oReturn["UserName"].ToString().ToLower()); } } catch { } return(users.ToArray()); }
public void SendCommand(string hostname, string command, Credential credential) { ConnectionOptions connectoptions = GetConnectionOptions(hostname, credential); connectoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", hostname), connectoptions); mgmtScope.Connect(); System.Management.ObjectGetOptions objectGetOptions = new System.Management.ObjectGetOptions(); System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath("Win32_Process"); System.Management.ManagementClass processClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, objectGetOptions); System.Management.ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); ManagementClass startupInfo = new ManagementClass("Win32_ProcessStartup"); startupInfo.Properties["ShowWindow"].Value = 0; inParams["CommandLine"] = command; inParams["ProcessStartupInformation"] = startupInfo; processClass.InvokeMethod("Create", inParams, null); }
private bool setBrightness(int brightness) { byte brightnessInBytes; if (brightness >= 0 && brightness <= 100) { brightnessInBytes = (byte)(brightness); } else { return(false); } try { /* DANGER ZONE CODE - Only about 80% sure what this does */ System.Management.ManagementScope scope = new System.Management.ManagementScope("root\\WMI"); System.Management.SelectQuery query = new System.Management.SelectQuery("WmiMonitorBrightnessMethods"); System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(scope, query); System.Management.ManagementObjectCollection moc = mos.Get(); foreach (System.Management.ManagementObject o in moc) //Don't ask questions you don't want to know the answer to { o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, brightnessInBytes }); break; //Searously } moc.Dispose(); mos.Dispose(); /* END OF DANGER ZONE CODE */ } catch (Exception E) { Console.WriteLine(E.ToString()); return(false); } return(true); }
public static bool CreateUncShare(string shareName, string localPath) { ManagementScope scope = new System.Management.ManagementScope(@"root\CIMV2"); scope.Connect(); using (ManagementClass managementClass = new ManagementClass(scope, new ManagementPath("Win32_Share"), (ObjectGetOptions)null)) { SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, (SecurityIdentifier)null); byte[] binaryForm = new byte[securityIdentifier.BinaryLength]; securityIdentifier.GetBinaryForm(binaryForm, 0); using (ManagementObject wmiTrustee = new ManagementClass(scope, new ManagementPath("Win32_Trustee"), (ObjectGetOptions)null).CreateInstance()) { wmiTrustee["SID"] = (object)binaryForm; using (ManagementObject wmiACE = new ManagementClass(scope, new ManagementPath("Win32_ACE"), (ObjectGetOptions)null).CreateInstance()) { wmiACE["AccessMask"] = 131241; //READ_CONTROL | FILE_READ | FILE_TRAVERSE | FILE_READ_EA | FILE_LIST_DIRECTORY wmiACE["AceFlags"] = 3; //OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE wmiACE["AceType"] = 0; //ACCESS_ALLOWED wmiACE["Trustee"] = wmiTrustee; using (ManagementObject wmiSecurityDescriptor = new ManagementClass(scope, new ManagementPath("Win32_SecurityDescriptor"), (ObjectGetOptions)null).CreateInstance()) { wmiSecurityDescriptor["ControlFlags"] = 4; wmiSecurityDescriptor["DACL"] = new ManagementObject[] { wmiACE }; using (ManagementBaseObject inParamsCreate = managementClass.GetMethodParameters("Create")) { inParamsCreate["Access"] = wmiSecurityDescriptor; inParamsCreate["Path"] = localPath; inParamsCreate["Name"] = shareName; inParamsCreate["Type"] = 0; inParamsCreate["Description"] = "TVServerXBMC share"; using (ManagementBaseObject outParams = managementClass.InvokeMethod("Create", inParamsCreate, (InvokeMethodOptions)null)) return((int)(uint)outParams["returnValue"] == 0); } } } } } }
public static void FreeSpaceNetwork2(string srvname) { try { ConnectionOptions conn = new ConnectionOptions(); string strNameSpace = @"\\"; if (srvname != "") { strNameSpace += srvname; } else { strNameSpace += "."; } strNameSpace += @"\root\cimv2"; System.Management.ManagementScope managementScope = new System.Management.ManagementScope(strNameSpace, conn); System.Management.ObjectQuery query = new System.Management.ObjectQuery("SELECT Caption FROM Win32_OperatingSystem"); ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(managementScope, query); ManagementObjectCollection moCollection = moSearcher.Get(); foreach (ManagementObject oReturn in moCollection) { //foreach (PropertyData prop in oReturn.Properties) //{ // Console.WriteLine(prop.Name + " " + prop.Value); //} Console.WriteLine("Drive {0}", oReturn["Name"].ToString()); Console.WriteLine("Drive {0}", oReturn["Description"].ToString()); Console.WriteLine(" File system: {0}", oReturn["FileSystem"].ToString()); Console.WriteLine(" Available space to current user:{0, 15} bytes", oReturn["FreeSpace"].ToString()); Console.WriteLine(" Total size of drive: {0, 15} bytes ", oReturn["Size"].ToString()); //Console.WriteLine(" Volume label: {0}", oReturn["VolumeName"].ToString()); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static ServerHost CreateInstance(string pServer, string pUserName, string pPassword, string pDomain) { System.Management.ManagementScope mgmtScope = null; if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "\\\\" + pServer + "\\" + CreatedWmiNamespace; ConnectionOptions connection = new ConnectionOptions(); connection.Username = pUserName; connection.Password = pPassword; connection.Authority = "ntlmdomain:" + pDomain; mgmtScope.Options = connection; } else { mgmtScope = statMgmtScope; } System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); return(new ServerHost(tmpMgmtClass.CreateInstance())); }
static void SetBrightness(byte targetBrightness) { //define scope (namespace) System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightnessMethods"); //output current brightness System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q); System.Management.ManagementObjectCollection moc = mos.Get(); foreach (System.Management.ManagementObject o in moc) { o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise! break; //only work on the first object } moc.Dispose(); mos.Dispose(); }
// Get screen brightness static int GetBrightness() { System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI"); // Define scope (namespace) System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness"); // Define query System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q); // Output current screen brightness System.Management.ManagementObjectCollection moc = mos.Get(); // Store result byte curBrightness = 0; foreach (System.Management.ManagementObject o in moc) { curBrightness = (byte)o.GetPropertyValue("CurrentBrightness"); break; // Only work on the first object } moc.Dispose(); mos.Dispose(); return((int)curBrightness); // Return current screen brightness }
/// <summary> /// 获取远程服务器上运行的camstar 服务 /// </summary> /// <param name="ip"></param> /// <returns></returns> public static IEnumerable <string> GetSvc(string ip) { var svc = new List <string>(); var co = new ConnectionOptions(); if (!string.IsNullOrEmpty(UserName)) { co.Username = Domain + "\\" + UserName; //连接需要的用户名 co.Password = PassWord; //连接需要的密码 } string connectString = "SELECT * FROM Win32_Service WHERE State='Running' and DisplayName like '%Camstar%'"; //查询字符串 System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + ip + "\\root\\cimv2", co); var oq = new System.Management.ObjectQuery(connectString); var query = new ManagementObjectSearcher(ms, oq); var queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { // string hardwareID = mo["HardwareID"]); //直接根据属性名得到属性的值 //遍历所有属性,得到所有属性的值 PropertyDataCollection searcherProperties = mo.Properties; foreach (PropertyData sp in searcherProperties) { if (sp.Name == "Name") { svc.Add(sp.Value.ToString()); } } } return(svc); }
private void testFunction() { ConnectionOptions oConn = new ConnectionOptions(); string hostname = ""; System.Management.ManagementScope scope = new System.Management.ManagementScope(@"\\" + hostname + @"\root\cimv2", oConn); scope.Connect(); ManagementClass registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null); ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue"); inParams["hDefKey"] = 0x80000002; // HKEY_LOCAL_MACHINE; inParams["sSubKeyName"] = "SOFTWARE\\Microsoft\\.NETFramework"; inParams["sValueName"] = "InstallRoot"; ManagementBaseObject outParams = registry.InvokeMethod("GetStringValue", inParams, null); if (outParams.Properties["sValue"].Value != null) { // output = outParams.Properties["sValue"].Value.ToString(); } }
static void Main(string[] args) { Console.WriteLine("Computer details retrieved using Windows Management Instrumentation (WMI)"); //Connect to the remote computer ConnectionOptions co = new ConnectionOptions(); co.Username = "******"; co.Password = "******"; string serverName = "servername"; System.Management.ManagementScope ms = new System.Management.ManagementScope(servername + "\\root\\cimv2", co); //Query remote computer across the connection System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms, oq); ManagementObjectCollection queryCollection1 = query1.Get(); foreach (ManagementObject mo in queryCollection1) { string[] ss = { "" }; mo.InvokeMethod("Reboot", ss); Console.WriteLine(mo.ToString()); } }
/// <summary> /// 重启操作系统 /// </summary> public static void RestartOpSystem(string ip) { var co = new ConnectionOptions(); if (!string.IsNullOrEmpty(UserName)) { co.Username = Domain + "\\" + UserName; //连接需要的用户名 co.Password = PassWord; //连接需要的密码 } string connectString = "SELECT * FROM Win32_OperatingSystem"; //查询字符串 System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + ip + "\\root\\cimv2", co); var oq = new System.Management.ObjectQuery(connectString); var query = new ManagementObjectSearcher(ms, oq); var queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { mo.InvokeMethod("Reboot", null); } }
internal static IList <IPEndPoint> GetEndPoints(Server server, IPBinding binding) { if (!binding.Address.Equals(IPAddress.Any) && !binding.Address.Equals(IPAddress.IPv6Any)) { return(new IPEndPoint[] { binding }); } ManagementPath path = new ManagementPath(string.Format("\\\\{0}\\root\\cimv2", server.Fqdn)); System.Management.ManagementScope scope = new System.Management.ManagementScope(path); IList <NetworkConnectionInfo> connectionInfo = NetworkConnectionInfo.GetConnectionInfo(scope); List <IPEndPoint> list = new List <IPEndPoint>(); foreach (NetworkConnectionInfo networkConnectionInfo in connectionInfo) { foreach (IPAddress address in networkConnectionInfo.IPAddresses) { list.Add(new IPEndPoint(address, binding.Port)); } } return(list); }
public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { this.InitializeObject(mgmtScope, path, null); }
public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { return(GetInstances(mgmtScope, null, selectedProperties)); }
public static Environment0Collection GetInstances(System.Management.ManagementScope mgmtScope, System.String[] selectedProperties) { return(GetInstances(mgmtScope, null, selectedProperties)); }
public EnvironmentWmi(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { this.InitializeObject(mgmtScope, path, getOptions); }
public EnvironmentWmi(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { this.InitializeObject(mgmtScope, path, null); }
public static Environment0Collection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { return(GetInstances(mgmtScope, condition, null)); }
public EnvironmentWmi(System.Management.ManagementScope mgmtScope, string keyName, string keyUserName) { this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EnvironmentWmi.ConstructPath(keyName, keyUserName)), null); }
public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { this.InitializeObject(mgmtScope, path, getOptions); }
public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { return(GetInstances(mgmtScope, condition, null)); }
public BcdStringElement(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { this.InitializeObject(mgmtScope, path, null); }
public BcdStringElement(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { this.InitializeObject(mgmtScope, path, getOptions); }