本文整理汇总了C#中System.Management.ManagementScope类的典型用法代码示例。如果您正苦于以下问题:C# ManagementScope类的具体用法?C# ManagementScope怎么用?C# ManagementScope使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ManagementScope类属于System.Management命名空间,在下文中一共展示了ManagementScope类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: ShowUserSID
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;
}
开发者ID:reticon,项目名称:CCMClient,代码行数:31,代码来源:SID.cs
示例2: Run
//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;
}
}
开发者ID:davidduffett,项目名称:dropkick,代码行数:29,代码来源:WmiProcess.cs
示例3: GetOperatingSystemInfo
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());
}
}
}
}
}
开发者ID:JKLFA,项目名称:Craig-s-Utility-Library,代码行数:32,代码来源:OperatingSystem.cs
示例4: checkAntiVirus
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;
}
开发者ID:jra89,项目名称:ass,代码行数:26,代码来源:WindowsSecurityChecks.cs
示例5: OnCommitted
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
}
开发者ID:psyCHOder,项目名称:conferencexp,代码行数:29,代码来源:RefServiceInstaller.cs
示例6: ObjectQuery
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;
}
开发者ID:5dollartools,项目名称:NAM,代码行数:31,代码来源:Disk.cs
示例7: GetScope
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;
}
开发者ID:b1thunt3r,项目名称:WinInfo,代码行数:25,代码来源:Wmi.cs
示例8: GetComPorts
/// <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;
}
开发者ID:AlloBardo,项目名称:robot-mitya,代码行数:32,代码来源:ConsoleSettingsHelper.cs
示例9: ConfigureMmioGap
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");
}
}
}
}
开发者ID:dhanzhang,项目名称:Windows-classic-samples,代码行数:27,代码来源:LinuxAffinityUtilities.cs
示例10: LoadBIOS
/// <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();
}
}
}
}
开发者ID:pengyancai,项目名称:cs-util,代码行数:33,代码来源:BIOS.cs
示例11: WmiWrapper
public WmiWrapper(ManagementPath path)
{
_scope = new ManagementScope(path)
{
Options = { Impersonation = ImpersonationLevel.Impersonate }
};
}
开发者ID:b1thunt3r,项目名称:WinInfo,代码行数:7,代码来源:WMIWrapper.cs
示例12: getVhdSettings
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);
}
}
开发者ID:jeffpatton1971,项目名称:mod-hyperv,代码行数:7,代码来源:functions.cs
示例13: GetManagementObjects
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;
}
}
开发者ID:Xamarui,项目名称:NewId,代码行数:30,代码来源:WMINetworkAddressWorkerIdProvider.cs
示例14: GetHotfixDetails
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;
}
开发者ID:5dollartools,项目名称:NAM,代码行数:31,代码来源:Hotfix.cs
示例15: StartDetection
/// <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);
}
});
}
开发者ID:GTRsdk,项目名称:HandBrake,代码行数:35,代码来源:DriveDetectService.cs
示例16: AddInsertUSBHandler
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;
}
}
开发者ID:sr3dna,项目名称:big5sync,代码行数:25,代码来源:DeviceWatcher.cs
示例17: GetBatteryPercent
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";
}
}
开发者ID:ethanhs,项目名称:IronShell,代码行数:35,代码来源:Battery.xaml.cs
示例18: USBRemoveWacher
/// <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();
};
}
开发者ID:fjkfjk,项目名称:ExerciseDemo,代码行数:31,代码来源:MainWindow.xaml.cs
示例19: Connect
/// <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);
}
}
开发者ID:jonaslsl,项目名称:modSIC,代码行数:29,代码来源:FileConnectionProvider.cs
示例20: MergeVirtualHardDisk
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);
}
}
}
}
开发者ID:dhanzhang,项目名称:Windows-classic-samples,代码行数:25,代码来源:MergeVirtualHardDisk.cs
注:本文中的System.Management.ManagementScope类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论