簡體   English   中英

WMI重新啟動遠程計算機

[英]WMI to reboot remote machine

我在舊線程上找到了以下代碼以關閉本地計算機:

using System.Management;

void Shutdown()
{
    ManagementBaseObject mboShutdown = null;
    ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
    mcWin32.Get();

    // You can't shutdown without security privileges
    mcWin32.Scope.Options.EnablePrivileges = true;
    ManagementBaseObject mboShutdownParams =
             mcWin32.GetMethodParameters("Win32Shutdown");

    // Flag 1 means we want to shut down the system. Use "2" to reboot.
    mboShutdownParams["Flags"] = "1";
    mboShutdownParams["Reserved"] = "0";
    foreach (ManagementObject manObj in mcWin32.GetInstances())
    {
        mboShutdown = manObj.InvokeMethod("Win32Shutdown", 
                                       mboShutdownParams, null);
    }
}

是否可以使用類似的WMI方法重新啟動遠程計算機的標志“ 2”,對於該計算機我僅具有計算機名稱,而沒有IP地址。

編輯:我目前有:

SearchResultCollection allMachinesCollected = machineSearch.FindAll();
Methods myMethods = new Methods();
string pcName;
ArrayList allComputers = new ArrayList();
foreach (SearchResult oneMachine in allMachinesCollected)
{
    //pcName = oneMachine.Properties.PropertyNames.ToString();
    pcName = oneMachine.Properties["name"][0].ToString();
    allComputers.Add(pcName);
    MessageBox.Show(pcName + "has been sent the restart command.");
    Process.Start("shutdown.exe", "-r -f -t 0 -m \\" + pcName);
}

但這是行不通的,我希望WMI向前發展。

要將WMI查詢尋址到遠程計算機,只需在ManagementScope對象中指定該計算機的名稱(或IP地址)。

我對C#不太了解,但這是我使用MSDN和WMI Code Creator提出的一個示例(順便說一句,這是生成WMI代碼的出色工具,並支持C#)。 希望這段代碼能給您帶來靈感。

免責聲明:此代碼未經測試。)

using System;
using System.Management;
...

void Shutdown()
{
    try
    {
        const string computerName = "COMPUTER"; // computer name or IP address

        ConnectionOptions options = new ConnectionOptions();
        options.EnablePrivileges = true;
        // To connect to the remote computer using a different account, specify these values:
        // options.Username = "USERNAME";
        // options.Password = "PASSWORD";
        // options.Authority = "ntlmdomain:DOMAIN";

        ManagementScope scope = new ManagementScope(
          "\\\\" + computerName +  "\\root\\CIMV2", options);
        scope.Connect();

        SelectQuery query = new SelectQuery("Win32_OperatingSystem");
        ManagementObjectSearcher searcher = 
            new ManagementObjectSearcher(scope, query);

        foreach (ManagementObject os in searcher.Get())
        {
            // Obtain in-parameters for the method
            ManagementBaseObject inParams = 
                os.GetMethodParameters("Win32Shutdown");

            // Add the input parameters.
            inParams["Flags"] =  2;

            // Execute the method and obtain the return values.
            ManagementBaseObject outParams = 
                os.InvokeMethod("Win32Shutdown", inParams, null);
        }
    }
    catch(ManagementException err)
    {
        MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
    }
    catch(System.UnauthorizedAccessException unauthorizedErr)
    {
        MessageBox.Show("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
    }
}

我對此也有麻煩。 WMI可能會誤導類和對象的方法。 我的解決方案是使用C#和WMI重新啟動網絡上的主機,但對於本地計算機卻很容易簡化:

private void rebootHost(string hostName)
{
    string adsiPath = string.Format(@"\\{0}\root\cimv2", hostName);
    ManagementScope scope = new ManagementScope(adsiPath);
    // I've seen this, but I found not necessary:
    // scope.Options.EnablePrivileges = true;
    ManagementPath osPath = new ManagementPath("Win32_OperatingSystem");
    ManagementClass os = new ManagementClass(scope, osPath, null);

    ManagementObjectCollection instances;
    try
    {
        instances = os.GetInstances();
    }
    catch (UnauthorizedAccessException exception)
    {
        throw new MyException("Not permitted to reboot the host: " + hostName, exception);
    }
    catch (COMException exception)
    {
        if (exception.ErrorCode == -2147023174)
        {
            throw new MyException("Could not reach the target host: " + hostName, exception);
        }
        throw; // Unhandled
    }
    foreach (ManagementObject instance in instances)
    {
        object result = instance.InvokeMethod("Reboot", new object[] { });
        uint returnValue = (uint)result;

        if (returnValue != 0)
        {
            throw new MyException("Failed to reboot host: " + hostName);
        }
    }
}

如果需要非WMI解決方案,則可以使用shutdown命令。

shutdown [{-l|-s|-r|-a}] [-f] [-m  [\\ComputerName]] [-t xx] [-c "message"] [-d[u][p]:xx:yy] 

使用-m關閉遠程計算機。

請參閱此鏈接以獲取更多信息。 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/shutdown.mspx

這將像sharm一樣工作

gwmi win32_operatingsystem -ComputerName xxxxxxxxxxxx | Invoke-WmiMethod -Name reboot

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM