本文整理汇总了C#中System.Management.ManagementScope.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# ManagementScope.Connect方法的具体用法?C# ManagementScope.Connect怎么用?C# ManagementScope.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Management.ManagementScope
的用法示例。
在下文中一共展示了ManagementScope.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
ConnectionOptions conn = new ConnectionOptions();
conn.Username = "kingsley";//登入远端电脑的账户
conn.Password = "111111";//登入远端电脑的密码
ManagementPath path = new ManagementPath();
//其中root\cimv2是固定写法
path.Path = @"\\10.0.1.36\root\cimv2";
ManagementScope ms = new ManagementScope();
ms.Options = conn;
ms.Path = path;
ms.Connect();
//这里的例子读取文件的最后修改日期
ObjectQuery query = new ObjectQuery("SELECT * FROM CIM_DataFile WHERE Name = 'C:\\\\KVOffice.txt'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms,query);
ManagementObjectCollection collection = searcher.Get();
string time = "";
foreach (ManagementObject obj in collection)
{
time = obj.Properties["LastModified"].Value.ToString().Substring(0,14);
}
Console.WriteLine("测试dev");
Console.WriteLine(time);
Console.ReadLine();
}
示例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;
}
}
示例3: AddARecord
public void AddARecord(string hostName, string zone, string iPAddress, string dnsServerName)
{
/*ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
connOptions.Username = "nwtraders\administrator";
connOptions.Password = "Password01";
*/
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);
}
示例4: StartService
public static void StartService(string service)
{
string msg = string.Format("starting up service begins: {0}", service);
Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg);
string objPath = string.Format("Win32_Service.Name='{0}'", service);
try
{
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Authentication = AuthenticationLevel.Packet;
connectionOptions.EnablePrivileges = true;
connectionOptions.Username = Singleton<Constants>.UniqueInstance.UserName;
connectionOptions.Password = Singleton<Constants>.UniqueInstance.PassWord;
connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", Singleton<Constants>.UniqueInstance.MachineName), connectionOptions);
scope.Connect();
using (ManagementObject serviceObj = new ManagementObject(scope, new ManagementPath(objPath), null))
{
ManagementBaseObject outParams = serviceObj.InvokeMethod("StartService",
null, null);
uint returnValue = (uint)outParams["ReturnValue"];
msg = string.Format("starting up result for service {0} is {1}", service, returnValue);
Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg, LogLevel.Warning);
}
}
catch (Exception ex)
{
msg = string.Format("error starting up service: {0}, {1}", service, ex);
Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg, LogLevel.Warning);
}
msg = string.Format("starting up service ends: {0}", service);
Singleton<ReportMediator>.UniqueInstance.ReportStatus(msg);
}
示例5: 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;
}
示例6: getComputerInfos
public static String[] getComputerInfos(string computername)
{
String[] computerInfos = new String[2];
ConnectionOptions connOptions = new ConnectionOptions();
ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
//To use caller credential
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", computername), connOptions);
manScope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection){
computerInfos[0] = Convert.ToString(m["Caption"]);
computerInfos[1] = Convert.ToString(m["Status"]);
}
return computerInfos;
}
示例7: GetManagementClass
public ManagementClass GetManagementClass(string scopeString, string classString, IPHostEntry hostEntry, string username, string password)
{
SetHost(hostEntry);
ValidateHost();
var connectionOptions = new ConnectionOptions()
{
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true,
Username = username,
Password = password
};
var managementScope = new ManagementScope(String.Format(@"\\{0}\{1}", _host, scopeString), connectionOptions);
var managementClass = new ManagementClass(managementScope, new ManagementPath(classString), new ObjectGetOptions());
managementScope.Connect();
if (!managementScope.IsConnected)
{
throw new InstrumentationException(ExceptionMessages.ScopeConnectFail);
}
return managementClass;
}
示例8: 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
}
示例9: CallWmiShutdown
private static void CallWmiShutdown(int flags)
{
// 実行前にガベージコレクトを行っておく
GC.Collect();
System.Threading.Thread.CurrentThread.Join(0);
GC.WaitForPendingFinalizers();
GC.Collect();
//ユーザー特権を有効にするための設定を作成
ConnectionOptions co = new ConnectionOptions();
co.Impersonation = ImpersonationLevel.Impersonate;
co.EnablePrivileges = true;
//ManagementScopeを作成
ManagementScope sc = new ManagementScope("\\ROOT\\CIMV2", co);
//接続
sc.Connect();
ObjectQuery oq = new ObjectQuery("select * from Win32_OperatingSystem");
using (ManagementObjectSearcher mos = new ManagementObjectSearcher(sc, oq)) {
//Shutdownメソッドを呼び出す
foreach (ManagementObject mo in mos.Get()) {
//パラメータを指定
ManagementBaseObject inParams = mo.GetMethodParameters("Win32Shutdown");
inParams["Flags"] = flags;
inParams["Reserved"] = 0;
//Win32Shutdownメソッドを呼び出す
ManagementBaseObject outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);
}
}
}
示例10: Start
public override Process[] Start(ProcessStartInfo psi)
{
List<Process> processes = new List<Process>();
ConnectionOptions options = GetConnectionOptions();
foreach (string comp in _computers)
{
_scope = GetScope(comp, options);
_scope.Connect();
try
{
Process process = CreateProcess(psi);
if (process != null)
{
processes.Add(process);
}
}
finally
{
_scope = null;
}
}
return processes.ToArray();
}
示例11: ConnectToClient
private ManagementScope ConnectToClient(string hostname)
{
ManagementPath oPath = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CCM", hostname));
ConnectionOptions oCon = new ConnectionOptions();
oCon.Impersonation = ImpersonationLevel.Impersonate;
oCon.EnablePrivileges = true;
ManagementScope oMs = new ManagementScope(oPath, oCon);
try
{
oMs.Connect();
}
catch (System.UnauthorizedAccessException ex)
{
return null;
}
catch (Exception e)
{
return null;
}
finally
{
GC.Collect();
}
return oMs;
}
示例12: Bob
public void Bob()
{
var connOptions = new ConnectionOptions
{
EnablePrivileges = true,
//Username = "username",
//Password = "password"
};
string server = "SrvTestWeb01";
ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", server), connOptions);
manScope.Connect();
var managementPath = new ManagementPath("Win32_Process");
var processClass = new ManagementClass(manScope, managementPath, new ObjectGetOptions());
var inParams = processClass.GetMethodParameters("Create");
inParams["CommandLine"] = @"C:\Temp\dropkick.remote\dropkick.remote.exe create_queue msmq://localhost/dk_test";
var outParams = processClass.InvokeMethod("Create", inParams, null);
var rtn = System.Convert.ToUInt32(outParams["returnValue"]);
var processID = System.Convert.ToUInt32(outParams["processId"]);
}
示例13: ConnectWMIScope
public static bool ConnectWMIScope(string RemoteServer, string UserName, String Password)
{
bool retval = true;
try
{
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Packet;
options.Username = UserName;
options.Password = Password;
options.Timeout = TimeSpan.FromSeconds(2);
string ConnectionString = string.Format("\\\\{0}\\root\\cimv2", RemoteServer);
ManagementScope scope = new ManagementScope(ConnectionString, options);
scope.Connect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
retval = false;
return retval;
}
return retval;
}
示例14: PrinterStatus
/// <summary>
/// Checks whether configured printer is connected to computer or not and return status
/// </summary>
/// <returns>CONNECTED if printer is online or else message</returns>
public static string PrinterStatus(string printerName)
{
// Set management scope
ManagementScope scope = new ManagementScope(@"\root\cimv2");
scope.Connect();
string result = string.Empty;
// Select Printers from WMI Object Collections
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
foreach (ManagementObject printer in searcher.Get())
{
printerName = printer["Name"].ToString().ToLower();
if (printerName.Equals(printerName))
{
if (printer["WorkOffline"].ToString().ToLower().Equals("true"))
{
// printer is offline by user
result = "Your Plug-N-Play printer is not connected.";
break;
}
else
{
// printer is not offline
result = "CONNECTED";
break;
}
}
}
return result;
}
示例15: FindProcess
public List<Process> FindProcess(string name, string remotemachine)
{
if ( String.IsNullOrEmpty(remotemachine))
{
return FindProcessOnLocalMachine(name);
}
ManagementScope scope = new ManagementScope("\\\\" + remotemachine + "\\root\\cimv2");
scope.Connect();
var result = new List<Process>();
string wmiQuery = string.Format("select ProcessId, CommandLine from Win32_Process where Name='{0}'", name);
ObjectQuery query = new ObjectQuery(wmiQuery);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection retObjectCollection = searcher.Get();
foreach (ManagementObject retObject in retObjectCollection)
{
string commandline = retObject["CommandLine"] as string;
string[] cols = commandline.Split('-');
var pid = retObject["ProcessId"];
var p = new Process()
{
Pid = (uint)retObject["ProcessId"],
Name = cols[1].Substring(3).Replace('"',' ' )
};
result.Add(p);
}
return result;
}