public async Task initConnection() { var timeOut = new TimeSpan(0, 5, 0); ConnectionOptions options = new ConnectionOptions(); options.Authority = "NTLMDOMAIN:" + remoteDomain.Trim(); options.Username = remoteUser.Trim(); options.Password = remotePass.Trim(); options.Impersonation = ImpersonationLevel.Impersonate; options.Timeout = timeOut; scope = new ManagementScope("\\\\" + remoteComputerName.Trim() + connectionNamespace, options); scope.Options.EnablePrivileges = true; scope2 = new ManagementScope("\\\\" + remoteComputerName.Trim() + "\\root\\default", options); scope2.Options.EnablePrivileges = true; try { await Task.Run(() => { scope.Connect(); }); } catch (Exception) { await Task.Run(() => { scope.Connect(); }); } }
public static ManagementScope ConnectionScope(string machineName, ConnectionOptions options, string path) { ManagementScope connectScope = new ManagementScope(); connectScope.Path = new ManagementPath(@"\\" + machineName + path); connectScope.Options = options; connectScope.Connect(); return connectScope; }
/// <summary> /// Gets the properties of an item at the specified path /// </summary> protected override void BeginProcessing() { ConnectionOptions options = GetConnectionOption(); if (this.AsJob) { RunAsJob("Get-WMIObject"); return; } else { if (List.IsPresent) { if (!this.ValidateClassFormat()) { ErrorRecord errorRecord = new ErrorRecord( new ArgumentException( String.Format( Thread.CurrentThread.CurrentCulture, "Class", this.Class)), "INVALID_QUERY_IDENTIFIER", ErrorCategory.InvalidArgument, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiFilterInvalidClass", this.Class); WriteError(errorRecord); return; } foreach (string name in ComputerName) { if (this.Recurse.IsPresent) { Queue namespaceElement = new Queue(); namespaceElement.Enqueue(this.Namespace); while (namespaceElement.Count > 0) { string connectNamespace = (string)namespaceElement.Dequeue(); ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, connectNamespace), options); try { scope.Connect(); } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); WriteError(errorRecord); continue; } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); WriteError(errorRecord); continue; } catch (System.UnauthorizedAccessException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", connectNamespace, e.Message); WriteError(errorRecord); continue; } ManagementClass namespaceClass = new ManagementClass(scope, new ManagementPath("__Namespace"), new ObjectGetOptions()); foreach (ManagementBaseObject obj in namespaceClass.GetInstances()) { if (!IsLocalizedNamespace((string)obj["Name"])) { namespaceElement.Enqueue(connectNamespace + "\\" + obj["Name"]); } } ManagementObjectSearcher searcher = this.GetObjectList(scope); if (searcher == null) { continue; } foreach (ManagementBaseObject obj in searcher.Get()) { WriteObject(obj); } } } else { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); try { scope.Connect(); } catch (ManagementException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); WriteError(errorRecord); continue; } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); WriteError(errorRecord); continue; } catch (System.UnauthorizedAccessException e) { ErrorRecord errorRecord = new ErrorRecord( e, "INVALID_NAMESPACE_IDENTIFIER", ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails(this, "WmiResources", "WmiNamespaceConnect", this.Namespace, e.Message); WriteError(errorRecord); continue; } ManagementObjectSearcher searcher = this.GetObjectList(scope); if (searcher == null) { continue; } foreach (ManagementBaseObject obj in searcher.Get()) { WriteObject(obj); } } } return; } // When -List is not specified and -Recurse is specified, we need the -Class parameter to compose the right query string if (this.Recurse.IsPresent && string.IsNullOrEmpty(Class)) { string errorMsg = string.Format(CultureInfo.InvariantCulture, WmiResources.WmiParameterMissing, "-Class"); ErrorRecord er = new ErrorRecord(new InvalidOperationException(errorMsg), "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } string queryString = string.IsNullOrEmpty(this.Query) ? GetQueryString() : this.Query; ObjectQuery query = new ObjectQuery(queryString.ToString()); foreach (string name in ComputerName) { try { ManagementScope scope = new ManagementScope(WMIHelper.GetScopeString(name, this.Namespace), options); EnumerationOptions enumOptions = new EnumerationOptions(); enumOptions.UseAmendedQualifiers = Amended; enumOptions.DirectRead = DirectRead; ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query, enumOptions); foreach (ManagementBaseObject obj in searcher.Get()) { WriteObject(obj); } } catch (ManagementException e) { ErrorRecord errorRecord = null; if (e.ErrorCode.Equals(ManagementStatus.InvalidClass)) { string className = GetClassNameFromQuery(queryString); string errorMsg = String.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, e.Message, className); errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidType, null); } else if (e.ErrorCode.Equals(ManagementStatus.InvalidQuery)) { string errorMsg = String.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, e.Message, queryString); errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); } else if (e.ErrorCode.Equals(ManagementStatus.InvalidNamespace)) { string errorMsg = String.Format(CultureInfo.InvariantCulture, WmiResources.WmiQueryFailure, e.Message, this.Namespace); errorRecord = new ErrorRecord(new ManagementException(errorMsg), "GetWMIManagementException", ErrorCategory.InvalidArgument, null); } else { errorRecord = new ErrorRecord(e, "GetWMIManagementException", ErrorCategory.InvalidOperation, null); } WriteError(errorRecord); continue; } catch (System.Runtime.InteropServices.COMException e) { ErrorRecord errorRecord = new ErrorRecord(e, "GetWMICOMException", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); continue; } } // foreach computerName } } // BeginProcessing
private void btnLogIn_Click(object sender, EventArgs e) { //using (CheckConnection chkConn = new CheckConnection()) //{ // chkConn.ShowDialog(); // if (chkConn.DialogResult == DialogResult.Cancel) // { // chkConn.Dispose(); // Application.Exit(); // return; // } //} string domainName = PSSClass.Security.GetDomainName(txtUserName.Text); // Extract domain name //form provide DomainUsername e.g Domainname\Username string userName = PSSClass.Security.GetUsername(txtUserName.Text); // Extract user name //from provided DomainUsername e.g Domainname\Username IntPtr token = IntPtr.Zero; bool result = LogonUser(userName, domainName, txtPassword.Text, 3, 1, ref token); if (result) { //Properties.Settings.Default.UserID = txtUserName.Text; nUserID = PSSClass.Users.UserID(txtUserName.Text); strUserID = txtUserName.Text; if (nUserID == 0) { MessageBox.Show("No user account found.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); this.Dispose(); this.DialogResult = DialogResult.Cancel; return; } this.DialogResult = DialogResult.OK; } else { nCtr += 1; if (nCtr == 3) { MessageBox.Show("Your account has been locked out." + Environment.NewLine + "Please contact the IT Department.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); LockWorkStation(); this.Dispose(); this.DialogResult = DialogResult.Cancel; Application.Exit(); return; } //If not authenticated then display an error message MessageBox.Show("Invalid account or password.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); txtPassword.Focus(); return; } string strCompName = System.Net.Dns.GetHostEntry("").HostName; DataTable dt = PSSClass.Users.UserCurrLogin(LogIn.nUserID); if (dt != null && dt.Rows.Count > 0 && dt.Rows[0]["LogType"].ToString() == "1" && strCompName != dt.Rows[0]["ComputerName"].ToString()) { DialogResult dReply = new DialogResult(); dReply = MessageBox.Show("You are currently logged in at workstation " + dt.Rows[0]["ComputerName"].ToString() + Environment.NewLine + "Do you want to login in this workstation?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dReply == DialogResult.No) { this.Dispose(); this.DialogResult = DialogResult.Cancel; return; } DialogResult dRes = new DialogResult(); dRes = MessageBox.Show("PTS would now be terminated at workstation " + dt.Rows[0]["ComputerName"].ToString() + Environment.NewLine + "Please confirm process to terminate PTS.", Application.ProductName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dRes == DialogResult.Cancel) { this.Dispose(); this.DialogResult = DialogResult.Cancel; return; } System.Management.ConnectionOptions connOptions = new ConnectionOptions(); connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; connOptions.Username = "******"; // pubUserName; connOptions.Password = "******"; // txtPassword.Text; ManagementScope scope = new ManagementScope("\\\\" + dt.Rows[0]["ComputerName"].ToString() + "\\root\\cimv2", connOptions); scope.Connect(); ObjectQuery query = new ObjectQuery("SELECT * FROM WIN32_PROCESS WHERE Name='PTS.exe'");//ControlPages.Exe//Name='GISMain.exe' OR ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection objectcollection = searcher.Get(); if (LogIn.strUserID != "rcarandang" && LogIn.strUserID != "mmoreno")//exclude Terminal Server { // foreach (ManagementObject Obj in objectcollection) // { // ManagementBaseObject outParams = Obj.InvokeMethod("GetOwner", null, null); // if (outParams["User"].ToString().ToUpper() == dt.Rows[0]["ComputerName"].ToString().ToUpper()) // { // Obj.InvokeMethod("Terminate", null); // } // } //} //else //{ foreach (ManagementObject Obj in objectcollection) { Obj.InvokeMethod("Terminate", null); } } //using (TerminateGIS xGIS = new TerminateGIS()) //{ // xGIS.Location = new Point(245, 250); // xGIS.pubComputer = dt.Rows[0]["ComputerName"].ToString(); // xGIS.pubUserName = txtUserName.Text; // if (xGIS.ShowDialog() == DialogResult.Cancel) // { // this.Dispose(); // this.DialogResult = DialogResult.Cancel; // return; // } //} dt.Dispose(); } ////Get File Version of the Current Application string strCurrFile = Application.StartupPath + @"\PTS.exe"; System.Reflection.Assembly assInfo = System.Reflection.Assembly.ReflectionOnlyLoadFrom(strCurrFile); System.Diagnostics.FileVersionInfo currFileVer = System.Diagnostics.FileVersionInfo.GetVersionInfo(assInfo.Location); string strCurrVer = currFileVer.FileVersion; SqlConnection sqlcnn = PSSClass.DBConnection.PSSConnection(); if (sqlcnn == null) { MessageBox.Show("Connection problen encountered." + Environment.NewLine + "Please try again later.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } SqlCommand sqlcmd = new SqlCommand(); sqlcmd.Connection = sqlcnn; sqlcmd.Parameters.AddWithValue("@UserID", nUserID); sqlcmd.Parameters.AddWithValue("@LType", 1); //sqlcmd.Parameters.AddWithValue("@FileVer", strCurrVer); sqlcmd.Parameters.AddWithValue("@CompName", strCompName); sqlcmd.CommandType = CommandType.StoredProcedure; sqlcmd.CommandText = "spUserLogInOut"; try { sqlcmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } sqlcmd.Dispose(); sqlcnn.Close(); sqlcnn.Dispose(); strPassword = txtPassword.Text; if (File.Exists(@"\\PSAPP01\PTS\Images\PSS Background New.jpg")) { File.Copy(@"\\PSAPP01\IT Files\PTS\Images\PSS Background New.jpg", Application.StartupPath + @"\PSS Background.jpg", true); } }
public static IEnumerable <AlarmDevice> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
/// <summary> /// Gets the PC data and sets the WinPC properties. /// </summary> /// <param name="strIP">The string ip.</param> public void GetPCSpecs(string strIP) { // Build the required objects to connect to the PC ConnectionOptions conOptions = new ConnectionOptions(); conOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope manScope = new ManagementScope(@"\\" + strIP + @"\root\cimv2", conOptions); manScope.Connect(); if (manScope.IsConnected) { // Build the required objects to make the call to WMI ObjectQuery query; ManagementObjectSearcher searcher; ManagementObjectCollection queryCollection; // Set the IP this.IPAddress = strIP; // Get the PC name query = new ObjectQuery("SELECT Name FROM Win32_ComputerSystem"); searcher = new ManagementObjectSearcher(manScope, query); queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { this.PCName = m["Name"].ToString(); } // Get CPU Information query = new ObjectQuery("SELECT * FROM Win32_Processor"); searcher = new ManagementObjectSearcher(manScope, query); queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { this.CPUName = m["Name"].ToString(); this.CPUAddressWidth = m["AddressWidth"].ToString(); this.CPUCores = m["NumberOfCores"].ToString(); } // Get OS Information query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); searcher = new ManagementObjectSearcher(manScope, query); queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { this.OS = m["Caption"].ToString(); this.OSInstallDate = m["InstallDate"].ToString(); } // Get RAM Information query = new ObjectQuery("SELECT * FROM Win32_PhysicalMemory"); searcher = new ManagementObjectSearcher(manScope, query); queryCollection = searcher.Get(); long actualGbsRam = 0; foreach (ManagementObject m in queryCollection) { string strCapacity = m["Capacity"].ToString(); long gbsRam = ((Convert.ToInt64(strCapacity) / 1024) / 1024) / 1024; actualGbsRam += gbsRam; // this.strRAMCapacity += gbsRam.ToString(); this.RAMInstalled = actualGbsRam.ToString() + " GB"; } // Get Motherboard Information query = new ObjectQuery("SELECT * FROM Win32_BaseBoard"); searcher = new ManagementObjectSearcher(manScope, query); queryCollection = searcher.Get(); foreach (ManagementObject m in queryCollection) { this.MoboMfg = m["Manufacturer"].ToString(); this.MoboProduct = m["Product"].ToString(); } } }
public static IEnumerable <PowerMeterCounter> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public List <accounts> WMI_REG(string remoteHostName, string userName, string password, string basekey, string key) { List <accounts> acc = new List <accounts>(); ManagementScope ms = null; ConnectionOptions wmiServiceOptions = new ConnectionOptions(); wmiServiceOptions.Impersonation = ImpersonationLevel.Impersonate; wmiServiceOptions.Authentication = AuthenticationLevel.PacketPrivacy; string connectionString = string.Format("\\\\{0}\\root\\default", remoteHostName); try { if (remoteHostName != "." && remoteHostName != "localhost" && userName != "$using current credentials") { wmiServiceOptions.Username = userName; wmiServiceOptions.Password = password; ms = new ManagementScope(connectionString, wmiServiceOptions); } else { ms = new ManagementScope(connectionString, wmiServiceOptions); } ManagementClass registry = new ManagementClass(ms, new ManagementPath("StdRegProv"), null); //ManagementBaseObject inParams= //ManagementBaseObject inParams = registry.GetMethodParameters("GetStringValue"); ManagementBaseObject inParams = registry.GetMethodParameters("EnumKey"); Console.WriteLine("Returning a specific value for a specified key is done"); uint HKEY = new uint(); if (basekey == "HKLM") { HKEY = LOCAL_MACHINE; } if (basekey == "HKCU") { HKEY = CURRENT_USER; } inParams.SetPropertyValue("hDefKey", HKEY); inParams.SetPropertyValue("sSubKeyName", key); //inParams["hDefKey"] = LOCAL_MACHINE; //inParams["sSubKeyName"] = key; string[] error = (string[])registry.InvokeMethod("EnumKey", inParams, null).Properties["sNames"].Value; foreach (string k in error) { try { if (k.Contains("Data")) { accounts resultItem = new accounts(); //string[] subs = (string[])registry.InvokeMethod("EnumKey", inParams, null).Properties["sNames"].Value; inParams = registry.GetMethodParameters("EnumValues"); inParams.SetPropertyValue("hDefKey", LOCAL_MACHINE); inParams.SetPropertyValue("sSubKeyName", key + "\\" + k); Type t = resultItem.GetType(); string[] information = (string[])registry.InvokeMethod("EnumValues", inParams, null).Properties["sNames"].Value; //string[] types = (string[])registry.InvokeMethod("EnumValues", inParams, null).Properties["Types"].Value; foreach (PropertyInfo p in t.GetProperties()) { for (int i = 0; i < information.Length; i++) { if (p.Name == information[i]) { uint youint = System.Convert.ToUInt32(inParams["hDefKey"].ToString()); inParams = registry.GetMethodParameters("GetStringValue"); inParams.SetPropertyValue("hDefKey", LOCAL_MACHINE); inParams.SetPropertyValue("sSubKeyName", key + "\\" + k); inParams.SetPropertyValue("sValueName", p.Name); RegType rType = GetValueType(registry, youint, inParams["sSubKeyName"].ToString(), inParams["sValueName"].ToString()); ManagementClass mc = registry; object oValue = null; try { switch (rType) { case RegType.REG_SZ: ManagementBaseObject outParams = mc.InvokeMethod("GetStringValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["sValue"]; } else { // GetStringValue call failed } break; case RegType.REG_EXPAND_SZ: outParams = mc.InvokeMethod("GetExpandedStringValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["sValue"]; } else { // GetExpandedStringValue call failed } break; case RegType.REG_MULTI_SZ: outParams = mc.InvokeMethod("GetMultiStringValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["sValue"]; } else { // GetMultiStringValue call failed } break; case RegType.REG_DWORD: outParams = mc.InvokeMethod("GetDWORDValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["uValue"]; } else { // GetDWORDValue call failed } break; case RegType.REG_BINARY: outParams = mc.InvokeMethod("GetBinaryValue", inParams, null); if (Convert.ToUInt32(outParams["ReturnValue"]) == 0) { oValue = outParams["uValue"] as byte[]; } else { // GetBinaryValue call failed } break; } p.SetValue(resultItem, oValue, null); //p.SetValue(resultItem, this.FixString(registry.InvokeMethod("GetStringValue", inParams, null).Properties["sValue"].Value), null); //p.SetValue(resultItem, this.FixString(registry.InvokeMethod("GetBinaryValue", inParams, null).Properties["sValue"].Value), null); } catch { } break; } } } if (resultItem.Pattern.Length > 0) { Array.Reverse(resultItem.Pattern); //bootkey << System.Convert.ToInt16(resultItem.Pattern); acc.Add(resultItem); } } } catch { } } ////inParams["sValueName"] = keyToRead; //Console.WriteLine("Invoking Method"); ////object[] args; //ManagementBaseObject outParams = registry.InvokeMethod("EnumKey", inParams, null); //Console.WriteLine("Invoking Method"); //Console.WriteLine(outParams["sValue"].ToString()); //error[0] = outParams["sValue"].ToString(); // } // catch (Exception ex) // { // } } catch (Exception e) { Console.WriteLine("[-] Error!"); } return(acc); }
public static IEnumerable <SqlServerMemoryNode> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public ManagementEventWatcher(ManagementScope scope, EventQuery query) {}
public static string GetPhysicalMemory() { ManagementScope oMs = new ManagementScope(); ObjectQuery oQuery = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory"); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery); ManagementObjectCollection oCollection = oSearcher.Get(); long MemSize = 0; long mCap = 0; // In case more than one Memory sticks are installed foreach (ManagementObject obj in oCollection) { mCap = Convert.ToInt64(obj["Capacity"]); MemSize += mCap; } MemSize = (MemSize / 1024) / 1024; return MemSize.ToString() + "MB"; }
public ManagementScopeIdParameter(ManagementScope managementScope) : base(managementScope.Id) { }
public static IEnumerable <SoftwareElementChecks> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public static IEnumerable <MonitorSetting> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options) { }
public MetricServiceCapabilities(ManagementScope mgmtScope, ManagementPath path, ObjectGetOptions getOptions) : base(mgmtScope, path, getOptions, ClassName) { }
public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query) {}
public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query, EnumerationOptions options) {}
private IEnumerable<ManagementObject> GetWmiObject(string query, string machineName, string rootPath) { try { var conn = new ConnectionOptions(); var path = string.Format(@"\\{0}\{1}", machineName, rootPath); if (!string.IsNullOrEmpty(this.Username)) { conn.Username = this.Username; } var pwd = this.Decrypt(this.Password); if (!string.IsNullOrEmpty(pwd)) { conn.Password = pwd; } path = string.Format(@"\\{0}\{1}", this.Hostname, rootPath); var scope = new ManagementScope(path, conn); this.Log.Debug(string.Format("{0} {1}", path, query)); var queryObject = new ObjectQuery(query); var searcher = new ManagementObjectSearcher(scope, queryObject); return searcher.Get().Cast<ManagementObject>().ToList(); } catch (Exception e) { this.Log.Debug(e); throw; } }
/// <summary> /// Connect method invoked by WinCs. /// </summary> /// /// <param name="taskId">Database assigned task Id.</param> /// <param name="connectionParameterSets">List of credential sets to use for connecting to the /// remote database server.</param> /// <param name="tftpDispatcher">TFTP transfer request listener for dispatching TFTP transfer /// requests.</param> /// /// <returns>Operation results.</returns> public ConnectionScriptResults Connect( long taskId, IDictionary <string, string>[] connectionParameterSets, string tftpPath, string tftpPath_login, string tftpPath_password, ITftpDispatcher tftpDispatcher) { Stopwatch executionTimer = Stopwatch.StartNew(); string taskIdString = taskId.ToString(); Lib.Logger.TraceEvent(TraceEventType.Start, 0, "Task Id {0}: Connection script ConnIISScript.", taskIdString); ConnectionScriptResults result = null; if (null == connectionParameterSets) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Null credential set passed to ConnIISScript", taskIdString); result = new ConnectionScriptResults(null, ResultCodes.RC_NULL_PARAMETER_SET, 0, -1); } else { try { bool isIISConnectionError = false; ResultCodes resultCode = ResultCodes.RC_HOST_CONNECT_FAILED; Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Executing ConnIISScript with {1} credential sets.", taskIdString, connectionParameterSets.Length.ToString()); //IDictionary<string, string>[] orderedConnectionParameterSets = this.reorderCredentials(connectionParameterSets); List <int> orderedConnections = this.reorderCredentials(connectionParameterSets); // // Loop to process credential sets until a successful // WMI connection is made. for (int j = 0; orderedConnections.Count > j; ++j) { ConnectionOptions co = new ConnectionOptions(); co.Impersonation = ImpersonationLevel.Impersonate; co.Authentication = AuthenticationLevel.Packet; co.Timeout = Lib.WmiConnectTimeout; co.EnablePrivileges = true; // @todo configuration isIISConnectionError = false; int i = orderedConnections[j]; string userName = connectionParameterSets[i][@"userName"]; string password = connectionParameterSets[i][@"password"]; if (null != userName && null != password && !("." == userName && "." == password)) { co.Username = userName; co.Password = password; } Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Processing credential set {1}: user=\"{2}\".", taskIdString, i.ToString(), userName); if (string.IsNullOrEmpty(userName)) { Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Unexpected Error: Receiving null username at Credential set {1}: user=\"{2}\".", taskIdString, i.ToString(), userName); continue; } Stopwatch sw = new Stopwatch(); ManagementPath mp = null; try { string server = connectionParameterSets[i][@"address"]; string domain = string.Empty; if (connectionParameterSets[i].ContainsKey(@"osWkgrpDomain")) { domain = connectionParameterSets[i][@"osWkgrpDomain"]; if (domain == @"__BDNA_DEFAULT__") { domain = ""; } } Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Attempting connection to computer in domain {1}.", taskIdString, domain); // // Create a scope for the cimv2 namespace. mp = new ManagementPath(); mp.Server = server; mp.NamespacePath = ManagementScopeNames.CIMV; ManagementScope cimvScope = new ManagementScope(mp, co); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Attempting connection to namespace {1}.", taskIdString, mp.ToString()); sw.Start(); cimvScope.Connect(); sw.Stop(); Debug.Assert(cimvScope.IsConnected); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.", taskIdString, mp.ToString(), sw.Elapsed.ToString()); // // Create a scope for the default namespace. mp = new ManagementPath(); mp.Server = server; mp.NamespacePath = ManagementScopeNames.DEFAULT; ManagementScope defaultScope = new ManagementScope(mp, co); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Attempting connection to namespace {1}.", taskIdString, mp.ToString()); sw.Reset(); defaultScope.Connect(); sw.Stop(); Debug.Assert(defaultScope.IsConnected); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.", taskIdString, mp.ToString(), sw.Elapsed.ToString()); // // Create a scope for the IIS namespace. mp = new ManagementPath(); mp.Server = server; mp.NamespacePath = @"root\MicrosoftIISV2"; co.Authentication = AuthenticationLevel.PacketPrivacy; ManagementScope iisScope = new ManagementScope(mp, co); try { Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Attempting connection to namespace {1}.", taskIdString, mp.ToString()); sw.Reset(); iisScope.Connect(); sw.Stop(); Debug.Assert(iisScope.IsConnected); Lib.Logger.TraceEvent(TraceEventType.Information, 0, "Task Id {0}: Connect to {1} succeeded. Elapsed time {2}.", taskIdString, mp.ToString(), sw.Elapsed.ToString()); } catch (Exception ex) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connect to IIS namespace: {1} failed. Elapsed time {2}.", taskIdString, mp.ToString(), sw.Elapsed.ToString()); resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; isIISConnectionError = true; throw ex; } // // We have everything we need. Create a dictionary // to return as the "connection" and get out of // loop. Dictionary <string, object> connectionDic = new Dictionary <string, object>(); foreach (KeyValuePair <string, string> kvp in connectionParameterSets[i]) { connectionDic.Add(kvp.Key, kvp.Value); } connectionDic[@"cimv2"] = cimvScope; connectionDic[@"default"] = defaultScope; connectionDic[@"iis"] = iisScope; result = new ConnectionScriptResults(connectionDic, ResultCodes.RC_SUCCESS, 0, i); break; } catch (ManagementException me) { if (ManagementStatus.AccessDenied == me.ErrorCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connect to {1} failed. Elapsed time {2}.\nWMI Error Code {3}", taskIdString, mp.ToString(), sw.Elapsed.ToString(), me.ErrorCode.ToString()); if (!isIISConnectionError) { resultCode = ResultCodes.RC_LOGIN_FAILED; } else { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; } } else { Lib.LogManagementException(taskIdString, sw, String.Format("Connect to {0} failed.", mp.ToString()), me); //break ; } } catch (UnauthorizedAccessException uae) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connect to {1} failed. Elapsed time {2}.\nMessage: {3}.", taskIdString, mp.ToString(), sw.Elapsed.ToString(), uae.Message); if (!isIISConnectionError) { resultCode = ResultCodes.RC_LOGIN_FAILED; } else { resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED; } } catch (COMException ce) { if (0x800706BA == (UInt32)ce.ErrorCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connect to {1} failed. Elapsed time {2}.\nCOM Exception {3}.\n" + "WMI port (135) may be closed or DCOM may not be properly configured", taskIdString, mp.ToString(), sw.Elapsed.ToString(), ce.Message); } else if (0x80040154 == (UInt32)ce.ErrorCode) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Connect to {1} failed. Elapsed time {2}.\nCOM Exception {3}.\n" + "WMI Management Class not registered. WMI provider not found on the remote machine.", taskIdString, mp.ToString(), sw.Elapsed.ToString(), ce.Message); } else { Lib.LogException(taskIdString, sw, String.Format("Connect to {0} failed", mp.ToString()), ce); } //break; } catch (Exception ex) { Lib.LogException(taskIdString, sw, String.Format("Connect to {0} failed", mp.ToString()), ex); //break; } } // // Connect failed after all credentials attempted. if (null == result) { result = new ConnectionScriptResults(null, resultCode, 0, connectionParameterSets.Length); } } catch (Exception e) { Lib.Logger.TraceEvent(TraceEventType.Error, 0, "Task Id {0}: Unhandled exception in ConnIISScript.\n{1}", taskIdString, e.ToString()); // // This is really an unanticipated fail safe. We're // going to report that *no* credentials were tried, which // actually may not be true... result = new ConnectionScriptResults(null, ResultCodes.RC_PROCESSING_EXCEPTION, 0, -1); } } Debug.Assert(null != result); Lib.Logger.TraceEvent(TraceEventType.Stop, 0, "Task Id {0}: Connection script ConnIISScript. Elapsed time {1}. Result code {2}.", taskIdString, executionTimer.Elapsed.ToString(), result.ResultCode.ToString()); return(result); }
public static string GetMotherBoardID() { string mbInfo = String.Empty; ManagementScope scope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2"); scope.Connect(); ManagementObject wmiClass = new ManagementObject(scope, new ManagementPath("Win32_BaseBoard.Tag=\"Base Board\""), new ObjectGetOptions()); foreach (PropertyData propData in wmiClass.Properties) { if (propData.Name == "SerialNumber") mbInfo = String.Format("{0}", Convert.ToString(propData.Value).Trim()).Replace('-', '#'); ; } return mbInfo; }
public static IEnumerable <NotifyFilterArrival> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\wmi")); return(Retrieve(managementScope)); }
private void ConnectIcs() { if (connectionComboBox.SelectedItem.ToString() == "No connection Avilable!") { StatusLbl.Text = "Status: Hotspot started without ICS!"; startButton.Text = "&Stop"; startButton.Enabled = true; } else { StatusLbl.Text = "Status: Trying to create ICS with " + connectionComboBox.SelectedItem.ToString() + "."; //------------------------------------------------------------------------------------------------------ ManagementScope IcsVirtualAdapterScope = new ManagementScope(); SelectQuery IcsVirtualAdapterQuery = new SelectQuery("Win32_NetworkAdapter", "Description=\"Microsoft Hosted Network Virtual Adapter\""); ManagementObjectSearcher IcsVirtualAdapterSearcher = new ManagementObjectSearcher(IcsVirtualAdapterScope, IcsVirtualAdapterQuery); //Dim IcsVirtualAdapterIdArray As New ComboBox try { foreach (ManagementObject IcsVirtualAdapter in IcsVirtualAdapterSearcher.Get()) { string IcsVirtualAdapterId = IcsVirtualAdapter["NetConnectionID"].ToString(); MainModule.IcsVirtualAdapterIdArray.Items.Add(IcsVirtualAdapterId); } } catch { } if (MainModule.IcsVirtualAdapterIdArray.Items.Count > 1) { VirtualAdapterSelectionDialog.DefaultInstance.ShowDialog(); } else { MainModule.IcsVirtualAdapterIdArray.SelectedIndex = 0; MainModule.IcsVirtualAdapterId = MainModule.IcsVirtualAdapterIdArray.SelectedItem.ToString(); } MainModule.IcsVirtualAdapterIdArray.Items.Clear(); StatusLbl.Text = "Status: Selected virtual adapter: " + MainModule.IcsVirtualAdapterId + "."; //------------------------------------------------------------------------------------------------------ try { IcsManager.ShareConnection(IcsManager.GetConnectionByName(connectionComboBox.SelectedItem.ToString()), IcsManager.GetConnectionByName(MainModule.IcsVirtualAdapterId)); StatusLbl.Text = "Status: Shared internet from " + connectionComboBox.SelectedItem.ToString() + " to " + MainModule.IcsVirtualAdapterId.ToString() + "."; startButton.Text = "&Stop"; startButton.Enabled = true; } catch { StatusLbl.Text = "Status: Network shell busy, retrying ICS with " + connectionComboBox.SelectedItem.ToString() + "."; //startButton.Text = "&Stop" //startButton.Enabled = True System.Threading.Thread.Sleep(1000); ConnectIcs(); } } }
public static IEnumerable <RedundancyComponent> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public WbemService(ManagementScope scope) { this.scope = scope; }
public static IEnumerable <LogonSession> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public static IEnumerable <HvMsrRead> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\wmi")); return(Retrieve(managementScope)); }
private void ConnectInvokeWmi() { ManagementObject managementObject; object obj; string str; InvokeWmiMethod invokeWmiMethod = (InvokeWmiMethod)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); if (invokeWmiMethod.InputObject == null) { ConnectionOptions connectionOption = invokeWmiMethod.GetConnectionOption(); ManagementPath managementPath = null; if (invokeWmiMethod.Path != null) { managementPath = new ManagementPath(invokeWmiMethod.Path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (invokeWmiMethod.namespaceSpecified) { InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath"); this.internalException = invalidOperationException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { managementPath.NamespacePath = invokeWmiMethod.Namespace; } if (!(managementPath.Server != ".") || !invokeWmiMethod.serverNameSpecified) { if (!(managementPath.Server == ".") || !invokeWmiMethod.serverNameSpecified) { this.computerName = managementPath.Server; } } else { InvalidOperationException invalidOperationException1 = new InvalidOperationException("ComputerNameSpecifiedWithPath"); this.internalException = invalidOperationException1; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } bool flag = false; bool enablePrivilege = false; Win32Native.TOKEN_PRIVILEGE tOKENPRIVILEGE = new Win32Native.TOKEN_PRIVILEGE(); try { try { enablePrivilege = this.NeedToEnablePrivilege(this.computerName, invokeWmiMethod.Name, ref flag); if (!enablePrivilege || flag && ComputerWMIHelper.EnableTokenPrivilege("SeShutdownPrivilege", ref tOKENPRIVILEGE) || !flag && ComputerWMIHelper.EnableTokenPrivilege("SeRemoteShutdownPrivilege", ref tOKENPRIVILEGE)) { if (invokeWmiMethod.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, invokeWmiMethod.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(invokeWmiMethod.Class); managementObject = managementClass; managementObject.Scope = managementScope; } else { managementPath.Server = this.computerName; if (!managementPath.IsClass) { ManagementObject managementObject1 = new ManagementObject(managementPath); managementObject = managementObject1; } else { ManagementClass managementClass1 = new ManagementClass(managementPath); managementObject = managementClass1; } ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption); managementObject.Scope = managementScope1; } ManagementBaseObject methodParameters = managementObject.GetMethodParameters(invokeWmiMethod.Name); if (invokeWmiMethod.ArgumentList != null) { int length = (int)invokeWmiMethod.ArgumentList.Length; foreach (PropertyData property in methodParameters.Properties) { if (length == 0) { break; } property.Value = invokeWmiMethod.ArgumentList[(int)invokeWmiMethod.ArgumentList.Length - length]; length--; } } if (!enablePrivilege) { managementObject.InvokeMethod(this.results, invokeWmiMethod.Name, methodParameters, null); } else { ManagementBaseObject managementBaseObject = managementObject.InvokeMethod(invokeWmiMethod.Name, methodParameters, null); int num = Convert.ToInt32(managementBaseObject["ReturnValue"], CultureInfo.CurrentCulture); if (num == 0) { this.ShutdownComplete.SafeInvoke <EventArgs>(this, null); } else { Win32Exception win32Exception = new Win32Exception(num); this.internalException = win32Exception; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } } else { string privilegeNotEnabled = ComputerResources.PrivilegeNotEnabled; string str1 = this.computerName; if (flag) { obj = "SeShutdownPrivilege"; } else { obj = "SeRemoteShutdownPrivilege"; } string str2 = StringUtil.Format(privilegeNotEnabled, str1, obj); InvalidOperationException invalidOperationException2 = new InvalidOperationException(str2); this.internalException = invalidOperationException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.internalException = cOMException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; this.internalException = unauthorizedAccessException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } finally { if (enablePrivilege) { if (flag) { str = "SeShutdownPrivilege"; } else { str = "SeRemoteShutdownPrivilege"; } ComputerWMIHelper.RestoreTokenPrivilege(str, ref tOKENPRIVILEGE); } } return; } else { try { ManagementBaseObject methodParameters1 = invokeWmiMethod.InputObject.GetMethodParameters(invokeWmiMethod.Name); if (invokeWmiMethod.ArgumentList != null) { int length1 = (int)invokeWmiMethod.ArgumentList.Length; foreach (PropertyData argumentList in methodParameters1.Properties) { if (length1 == 0) { break; } argumentList.Value = invokeWmiMethod.ArgumentList[(int)invokeWmiMethod.ArgumentList.Length - length1]; length1--; } } invokeWmiMethod.InputObject.InvokeMethod(this.results, invokeWmiMethod.Name, methodParameters1, null); } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; this.internalException = managementException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; this.internalException = cOMException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException3) { UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3; this.internalException = unauthorizedAccessException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; } }
public static IEnumerable <ProcessorAcpiXpssState> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\wmi")); return(Retrieve(managementScope)); }
private void ConnectRemoveWmi() { ManagementObject managementObject; RemoveWmiObject removeWmiObject = (RemoveWmiObject)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); if (removeWmiObject.InputObject == null) { ConnectionOptions connectionOption = removeWmiObject.GetConnectionOption(); ManagementPath managementPath = null; if (removeWmiObject.Path != null) { managementPath = new ManagementPath(removeWmiObject.Path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (removeWmiObject.namespaceSpecified) { InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath"); this.internalException = invalidOperationException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { managementPath.NamespacePath = removeWmiObject.Namespace; } if (!(managementPath.Server != ".") || !removeWmiObject.serverNameSpecified) { if (!(managementPath.Server == ".") || !removeWmiObject.serverNameSpecified) { this.computerName = managementPath.Server; } } else { InvalidOperationException invalidOperationException1 = new InvalidOperationException("ComputerNameSpecifiedWithPath"); this.internalException = invalidOperationException1; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } try { if (removeWmiObject.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, removeWmiObject.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(removeWmiObject.Class); managementObject = managementClass; managementObject.Scope = managementScope; } else { managementPath.Server = this.computerName; if (!managementPath.IsClass) { ManagementObject managementObject1 = new ManagementObject(managementPath); managementObject = managementObject1; } else { ManagementClass managementClass1 = new ManagementClass(managementPath); managementObject = managementClass1; } ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption); managementObject.Scope = managementScope1; } managementObject.Delete(this.results); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.internalException = cOMException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; this.internalException = unauthorizedAccessException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; } else { try { removeWmiObject.InputObject.Delete(this.results); } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; this.internalException = managementException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; this.internalException = cOMException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException3) { UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3; this.internalException = unauthorizedAccessException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; } }
public void servis_sorgula() { try { /*Bağlantı yapılıyor*/ ConnectionOptions baglanti = new ConnectionOptions(); baglanti.Username = textBox3.Text; baglanti.Password = textBox4.Text; baglanti.Authority = "ntlmdomain:" + textBox2.Text; if (textBox2.Text == "") { baglanti.Authority = ""; } string path = "\\\\" + textBox1.Text + "\\root" + "\\CIMV2"; ManagementScope scope = new ManagementScope( path, baglanti); // MessageBox.Show("Bağlantı Kuruluyor.. Servis Listesi Alınıyor ....."); scope.Connect(); /* * Servis listesi için sorgu oluşturulup managementonjseacher nesnesi tanımlanıyor. */ MessageBox.Show("bağlandı", "Bağlantı", MessageBoxButtons.OK, MessageBoxIcon.Information); ObjectQuery sorgu = new ObjectQuery( "SELECT * FROM Win32_Service"); ManagementObjectSearcher man_ob_arayici = new ManagementObjectSearcher(scope, sorgu); foreach (ManagementObject obj in man_ob_arayici.Get()) { listBox1.Items.Add(obj["Name"].ToString()); } label41.Text = listBox1.Items.Count.ToString(); /* * proccess bilgileri alınıyor. */ //MessageBox.Show("Bağlantı Kuruluyor.. Process Listesi Alınıyor ....."); ObjectQuery sorgu2 = new ObjectQuery("SELECT * FROM Win32_process"); ManagementObjectSearcher man_ob_arayici2 = new ManagementObjectSearcher(scope, sorgu2); foreach (ManagementObject obj in man_ob_arayici2.Get()) { listBox2.Items.Add(obj["Name"].ToString()); } label42.Text = listBox2.Items.Count.ToString(); //sistem bilgisi alınıyor //MessageBox.Show("Bağlantı Kuruluyor.. Sistem Bilgisi Alınıyor ....."); ObjectQuery sorgu4 = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher man_ob_arayici4 = new ManagementObjectSearcher(scope, sorgu4); foreach (ManagementObject obj in man_ob_arayici4.Get()) { label6.Text = obj["Caption"].ToString(); label8.Text = obj["OSArchitecture"].ToString(); label10.Text = obj["SerialNumber"].ToString(); label12.Text = obj["Version"].ToString(); label21.Text = obj["SystemDirectory"].ToString(); string total = (Convert.ToInt64(obj["TotalVisibleMemorySize"]) / (1024)).ToString(); string kalan = (Convert.ToInt64(obj["FreePhysicalMemory"]) / (1024)).ToString(); string kullanılan = (Convert.ToInt64(total) - Convert.ToInt64(kalan)).ToString(); toplam = total; kalann = kalan; ram_usage = kullanılan; label19.Text = kullanılan + " MB"; double yuzde = (Convert.ToDouble(Convert.ToDouble(kullanılan) / Convert.ToDouble(total)) * 100); double a = Math.Round(yuzde, 2); label15.Text = a.ToString() + " %"; } //Donanım bilgileri alınıyor. //MessageBox.Show("Bağlantı Kuruluyor.. Donanım Bilgileri Alınıyor ....."); ObjectQuery sorgu3 = new ObjectQuery("SELECT * FROM Win32_ComputerSystem"); ManagementObjectSearcher man_ob_arayici3 = new ManagementObjectSearcher(scope, sorgu3); foreach (ManagementObject obj in man_ob_arayici3.Get()) { label18.Text = (obj["NumberOfLogicalProcessors"].ToString()); label14.Text = (Convert.ToInt64(obj["TotalPhysicalMemory"]) / (1024 * 1024)).ToString() + " MB"; label29.Text = obj["Manufacturer"].ToString(); label27.Text = obj["Model"].ToString(); label25.Text = obj["Name"].ToString(); } //Bios bilgileri alınıyor. //MessageBox.Show("Bağlantı Kuruluyor.. BİOS Bilgileri Alınıyor ....."); ObjectQuery sorgu5 = new ObjectQuery("SELECT * FROM Win32_BIOS"); ManagementObjectSearcher man_ob_arayici5 = new ManagementObjectSearcher(scope, sorgu5); foreach (ManagementObject obj in man_ob_arayici5.Get()) { label23.Text = obj["Caption"].ToString(); label31.Text = obj["Manufacturer"].ToString(); label33.Text = obj["SerialNumber"].ToString(); } //MessageBox.Show("cpu usage"); ObjectQuery sorgu6 = new ObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor "); ManagementObjectSearcher man_ob_arayici6 = new ManagementObjectSearcher(scope, sorgu6); foreach (ManagementObject obj in man_ob_arayici6.Get()) { listBox3.Items.Add(obj["PercentProcessorTime"].ToString()); listBox4.Items.Add(obj["Name"].ToString()); } /* ObjectQuery sorgu7 = new ObjectQuery("SELECT * FROM Win32_Volume Where DriveLetter='C'"); * ManagementObjectSearcher man_ob_arayici7 = new ManagementObjectSearcher(scope, sorgu7); * foreach (ManagementObject obj in man_ob_arayici7.Get()) * { * int a = 1024 * 1024 * 1024; * long total_disk2 = Convert.ToInt64(obj["Size"].ToString())/a; * total_disk = total_disk2.ToString(); * long disk_space2 = Convert.ToInt64(obj["SizeRemaining"].ToString())/a; * disk_space = disk_space2.ToString(); * } * MessageBox.Show(total_disk.ToString()); * MessageBox.Show(disk_space.ToString()); */ /* ObjectQuery sorgu8 = new ObjectQuery("SELECT * FROM Win32_DiskDrive WHERE Model='" + label48.Text + "'"); * ManagementObjectSearcher man_ob_arayici8 = new ManagementObjectSearcher(scope, sorgu8); * foreach (ManagementObject obj in man_ob_arayici8.Get()) * { * //label48.Text = (obj["Model"].ToString()); * total_disk = (Convert.ToInt64(obj["Size"]) / 1024).ToString() + " GB"; * // disk_space = obj["FreeSpace"].ToString(); * } * * MessageBox.Show(disk_space);*/ } catch (ManagementException hata) { MessageBox.Show("Sorgu alınırken hata oluştu: " + hata.Message); } catch (System.UnauthorizedAccessException login_hata) { MessageBox.Show("Bağlantı hatası " + "(kullanıcı adı or parola hatalı): " + login_hata.Message); } }
private void ConnectGetWMI() { string wmiQueryString; GetWmiObjectCommand getWmiObjectCommand = (GetWmiObjectCommand)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); ConnectionOptions connectionOption = getWmiObjectCommand.GetConnectionOption(); SwitchParameter list = getWmiObjectCommand.List; if (!list.IsPresent) { if (string.IsNullOrEmpty(getWmiObjectCommand.Query)) { wmiQueryString = this.GetWmiQueryString(); } else { wmiQueryString = getWmiObjectCommand.Query; } string str = wmiQueryString; ObjectQuery objectQuery = new ObjectQuery(str.ToString()); try { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, getWmiObjectCommand.Namespace), connectionOption); EnumerationOptions enumerationOption = new EnumerationOptions(); enumerationOption.UseAmendedQualifiers = getWmiObjectCommand.Amended; enumerationOption.DirectRead = getWmiObjectCommand.DirectRead; ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery, enumerationOption); for (int i = 0; i < this.cmdCount; i++) { managementObjectSearcher.Get(this.results); } } catch (ManagementException managementException1) { ManagementException managementException = managementException1; this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.internalException = cOMException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; this.internalException = unauthorizedAccessException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; } else { if (getWmiObjectCommand.ValidateClassFormat()) { try { SwitchParameter recurse = getWmiObjectCommand.Recurse; if (!recurse.IsPresent) { ManagementScope managementScope1 = new ManagementScope(WMIHelper.GetScopeString(this.computerName, getWmiObjectCommand.Namespace), connectionOption); managementScope1.Connect(); ManagementObjectSearcher objectList = getWmiObjectCommand.GetObjectList(managementScope1); if (objectList != null) { objectList.Get(this.results); } else { throw new ManagementException(); } } else { ArrayList arrayLists = new ArrayList(); ArrayList arrayLists1 = new ArrayList(); ArrayList arrayLists2 = new ArrayList(); int num = 0; arrayLists.Add(getWmiObjectCommand.Namespace); bool flag = true; while (num < arrayLists.Count) { string item = (string)arrayLists[num]; ManagementScope managementScope2 = new ManagementScope(WMIHelper.GetScopeString(this.computerName, item), connectionOption); managementScope2.Connect(); ManagementClass managementClass = new ManagementClass(managementScope2, new ManagementPath("__Namespace"), new ObjectGetOptions()); foreach (ManagementBaseObject instance in managementClass.GetInstances()) { if (getWmiObjectCommand.IsLocalizedNamespace((string)instance["Name"])) { continue; } arrayLists.Add(string.Concat(item, "\\", instance["Name"])); } if (!flag) { arrayLists1.Add(this.Job.GetNewSink()); } else { flag = false; arrayLists1.Add(this.results); } arrayLists2.Add(managementScope2); num++; } if (arrayLists1.Count != arrayLists.Count || arrayLists2.Count != arrayLists.Count) { this.internalException = new InvalidOperationException(); this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } else { num = 0; while (num < arrayLists.Count) { ManagementObjectSearcher objectList1 = getWmiObjectCommand.GetObjectList((ManagementScope)arrayLists2[num]); if (objectList1 != null) { if (!flag) { objectList1.Get((ManagementOperationObserver)arrayLists1[num]); } else { flag = false; objectList1.Get(this.results); } num++; } else { num++; } } } } } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; this.internalException = managementException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; this.internalException = cOMException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException3) { UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3; this.internalException = unauthorizedAccessException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } return; } else { object[] @class = new object[1]; @class[0] = getWmiObjectCommand.Class; ArgumentException argumentException = new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, "Class", @class)); this.internalException = argumentException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } }
public static IEnumerable <ReceiveFilterGlobalParameters> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\wmi")); return(Retrieve(managementScope)); }
private void ConnectSetWmi() { ManagementObject value; SetWmiInstance setWmiInstance = (SetWmiInstance)this.wmiObject; this.state = WmiState.Running; this.RaiseWmiOperationState(null, WmiState.Running); if (setWmiInstance.InputObject == null) { ManagementPath managementPath = null; if (setWmiInstance.Class == null) { managementPath = new ManagementPath(setWmiInstance.Path); if (!string.IsNullOrEmpty(managementPath.NamespacePath)) { if (setWmiInstance.namespaceSpecified) { InvalidOperationException invalidOperationException = new InvalidOperationException("NamespaceSpecifiedWithPath"); this.internalException = invalidOperationException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { managementPath.NamespacePath = setWmiInstance.Namespace; } if (!(managementPath.Server != ".") || !setWmiInstance.serverNameSpecified) { if (!managementPath.IsClass) { if (!setWmiInstance.flagSpecified) { setWmiInstance.PutType = PutType.UpdateOrCreate; } else { if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate) { InvalidOperationException invalidOperationException1 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); this.internalException = invalidOperationException1; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } } else { if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly) { setWmiInstance.PutType = PutType.CreateOnly; } else { InvalidOperationException invalidOperationException2 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } } else { InvalidOperationException invalidOperationException3 = new InvalidOperationException("ComputerNameSpecifiedWithPath"); this.internalException = invalidOperationException3; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { if (setWmiInstance.flagSpecified && setWmiInstance.PutType != PutType.CreateOnly) { InvalidOperationException invalidOperationException4 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException4; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } setWmiInstance.PutType = PutType.CreateOnly; } if (managementPath != null && (!(managementPath.Server == ".") || !setWmiInstance.serverNameSpecified)) { this.computerName = managementPath.Server; } ConnectionOptions connectionOption = setWmiInstance.GetConnectionOption(); try { if (setWmiInstance.Path == null) { ManagementScope managementScope = new ManagementScope(WMIHelper.GetScopeString(this.computerName, setWmiInstance.Namespace), connectionOption); ManagementClass managementClass = new ManagementClass(setWmiInstance.Class); managementClass.Scope = managementScope; value = managementClass.CreateInstance(); } else { managementPath.Server = this.computerName; ManagementScope managementScope1 = new ManagementScope(managementPath, connectionOption); if (!managementPath.IsClass) { ManagementObject managementObject = new ManagementObject(managementPath); managementObject.Scope = managementScope1; try { managementObject.Get(); } catch (ManagementException managementException1) { ManagementException managementException = managementException1; if (managementException.ErrorCode == ManagementStatus.NotFound) { int num = setWmiInstance.Path.IndexOf(':'); if (num != -1) { int num1 = setWmiInstance.Path.Substring(num).IndexOf('.'); if (num1 != -1) { string str = setWmiInstance.Path.Substring(0, num1 + num); ManagementPath managementPath1 = new ManagementPath(str); ManagementClass managementClass1 = new ManagementClass(managementPath1); managementClass1.Scope = managementScope1; managementObject = managementClass1.CreateInstance(); } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } else { this.internalException = managementException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } value = managementObject; } else { ManagementClass managementClass2 = new ManagementClass(managementPath); managementClass2.Scope = managementScope1; value = managementClass2.CreateInstance(); } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator enumerator = setWmiInstance.Arguments.GetEnumerator(); while (enumerator.MoveNext()) { value[enumerator.Key as string] = enumerator.Value; } } PutOptions putOption = new PutOptions(); putOption.Type = setWmiInstance.PutType; if (value == null) { InvalidOperationException invalidOperationException5 = new InvalidOperationException(); this.internalException = invalidOperationException5; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } else { value.Put(this.results, putOption); } } catch (ManagementException managementException3) { ManagementException managementException2 = managementException3; this.internalException = managementException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException1) { COMException cOMException = cOMException1; this.internalException = cOMException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException1) { UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1; this.internalException = unauthorizedAccessException; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } else { ManagementObject value1 = null; try { PutOptions putType = new PutOptions(); if (setWmiInstance.InputObject.GetType() != typeof(ManagementClass)) { if (!setWmiInstance.flagSpecified) { setWmiInstance.PutType = PutType.UpdateOrCreate; } else { if (setWmiInstance.PutType != PutType.UpdateOnly && setWmiInstance.PutType != PutType.UpdateOrCreate) { InvalidOperationException invalidOperationException6 = new InvalidOperationException("NonUpdateFlagSpecifiedWithInstancePath"); this.internalException = invalidOperationException6; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } value1 = (ManagementObject)setWmiInstance.InputObject.Clone(); } else { if (!setWmiInstance.flagSpecified || setWmiInstance.PutType == PutType.CreateOnly) { value1 = ((ManagementClass)setWmiInstance.InputObject).CreateInstance(); setWmiInstance.PutType = PutType.CreateOnly; } else { InvalidOperationException invalidOperationException7 = new InvalidOperationException("CreateOnlyFlagNotSpecifiedWithClassPath"); this.internalException = invalidOperationException7; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); return; } } if (setWmiInstance.Arguments != null) { IDictionaryEnumerator dictionaryEnumerator = setWmiInstance.Arguments.GetEnumerator(); while (dictionaryEnumerator.MoveNext()) { value1[dictionaryEnumerator.Key as string] = dictionaryEnumerator.Value; } } putType.Type = setWmiInstance.PutType; if (value1 == null) { InvalidOperationException invalidOperationException8 = new InvalidOperationException(); this.internalException = invalidOperationException8; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } else { value1.Put(this.results, putType); } } catch (ManagementException managementException5) { ManagementException managementException4 = managementException5; this.internalException = managementException4; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (COMException cOMException3) { COMException cOMException2 = cOMException3; this.internalException = cOMException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } catch (UnauthorizedAccessException unauthorizedAccessException3) { UnauthorizedAccessException unauthorizedAccessException2 = unauthorizedAccessException3; this.internalException = unauthorizedAccessException2; this.state = WmiState.Failed; this.RaiseOperationCompleteEvent(null, OperationState.StopComplete); } } }
public ManagementEventWatcher(ManagementScope scope, EventQuery query, EventWatcherOptions options) {}
public static IEnumerable <SqlExpressTransactions> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public ManagementObject(ManagementScope scope, ManagementPath path, ObjectGetOptions options) {}
protected override void ProcessRecord() { // must use this to support processing record remotely. if (Remote) { ProcessRecordViaRest(); return; } // Validate / normalize inputs... int MaxMem; int MaxProc; int MaxDynMem; // Presently, I assume that values over 1TB (1024 * 1024 MB) were really intended to be sizes in bytes. if (Memory > (1024 * 1024)) { Memory /= (1024 * 1024); } if (DynamicMemoryLimit > (1024 * 1024)) { DynamicMemoryLimit /= (1024 * 1024); } // I'm using the OS version right now because I don't have a better way to determine Hyper-V capabilities. var SysVer = System.Environment.OSVersion; if (SysVer.Version.Major < 6) { // Not running at least Vista/2008, no Hyper-V available WriteWarning("This command only functions with Hyper-V on Windows Server 2008 and newer."); return; } switch (SysVer.Version.Minor) { case 0: // Vista / Server 2008 case 1: // Win7 / Server 2008 R2 MaxMem = MaxDynMem = 64 * 1024; // 64 GB limit MaxProc = 4; break; case 2: // Win8 / Server 2012 MaxMem = MaxDynMem = 1024 * 1024; // 1 TB limit MaxProc = 64; break; default: WriteWarning("Unknown version of Windows. No action taken."); return; } // Is Hyper-V available/installed? var scope = new ManagementScope(@"\\" + Environment.MachineName + @"\root"); scope.Connect(); if (!new ManagementObjectSearcher(scope, new SelectQuery("__Namespace", "Name like 'virtualization'")) .Get().Cast <ManagementObject>().Any()) { WriteWarning("Hyper-V not detected on this machine. Cannot continue."); return; } // Common items // Only 8 Synthetic NICs allowed if (NIC.Length > 8) { NIC = NIC.Take(8).ToArray(); } // Only 4 Legacy NICs allowed if (LegacyNIC.Length > 4) { LegacyNIC = LegacyNIC.Take(4).ToArray(); } if (Memory > MaxMem) { Memory = MaxMem; } if (DynamicMemoryLimit > MaxDynMem) { DynamicMemoryLimit = MaxDynMem; } if (Processors > MaxProc) { Processors = MaxProc; } // if (DynamicMemoryLimit < 1) DynamicMemoryLimit = Memory; var VM = Utility.NewVM(Name); if ( !VM.ModifyVMConfig(Processors, CPULimit, Memory, DynamicMemoryLimit > 0 ? (int?)DynamicMemoryLimit : null, DynamicMemory)) { VM.DestroyVM(); WriteWarning("Error in VM creation. See Hyper-V event log for details."); return; } string[] SCSI = new string[0]; string[] IDE0 = new string[0]; string[] IDE1 = new string[0]; if (VHD.Length > 4) { SCSI = VHD.Skip(4).ToArray(); VHD = VHD.Take(4).ToArray(); } if (VHD.Length > 2) { IDE1 = VHD.Skip(2).ToArray(); IDE0 = VHD.Take(2).ToArray(); } else { IDE0 = VHD; } // Attach IDE drives first var settings = VM.GetSettings(); var devices = VM.GetDevices(); ManagementObject[] IDEcontrolers = devices.Where( device => device != null && (device["ResourceSubType"] != null && device["ResourceSubType"].ToString() .Equals( Utility .ResourceSubTypes .ControllerIDE))) .ToArray(); foreach (string drive in IDE0.Where(drive => !String.IsNullOrEmpty(drive))) { if (!VM.AttachVHD(drive, IDEcontrolers[0])) { try { WriteWarning("Failed to attach drive to IDE controller 0: " + drive); } catch { } } } foreach (string drive in IDE1.Where(drive => !String.IsNullOrEmpty(drive))) { if (!VM.AttachVHD(drive, IDEcontrolers[1])) { try { WriteWarning("Failed to attach drive to IDE controller 1: " + drive); } catch { } } } // Attach SCSI controllers and drives int numCtrl = (SCSI.Length % 64 > 0) ? 1 : 0; numCtrl += SCSI.Length / 64; numCtrl = Math.Min(numCtrl, 4); // maximum of 4 SCSI controllers allowed in Hyper-V for (int i = 0; i < numCtrl; i++) { var SCSIctrlDef = VM.NewResource(Utility.ResourceTypes.ParallelSCSIHBA, Utility.ResourceSubTypes.ControllerSCSI, VM.GetScope()); SCSIctrlDef["Limit"] = 4; var SCSIctrl = VM.AddDevice(SCSIctrlDef); if (SCSIctrl == null) { WriteWarning("Failed to add SCSI controller (" + i + ")"); continue; } int num = Math.Min(SCSI.Length, 64); var tmp = SCSI.Take(num); SCSI = SCSI.Skip(num).ToArray(); foreach (string drive in tmp) { if (!VM.AttachVHD(drive, SCSIctrl)) { WriteWarning("Failed to attach drive to SCSI controller (" + i + "): " + drive); } } } // Add NICs foreach (string nic in NIC) { if (!VM.AddNIC(nic)) { WriteWarning("Failed to add Synthetic NIC: " + nic); } } foreach (string nic in LegacyNIC) { if (!VM.AddNIC(nic, true)) { WriteWarning("Failed to add Legacy NIC: " + nic); } } WriteObject(VM); }
public override bool SupportsScope(ManagementScope scope) { return true; }
public static IEnumerable <PhysicalPackage> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }
public override bool SupportsScope(ManagementScope scope) { return (scope == ManagementScope.Site) || (scope == ManagementScope.Server); }
public static IEnumerable <PnPDevicePropertyBoolean> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return(Retrieve(managementScope)); }