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”遥远的机器,因为只有机器名称,而不是IPaddress。

EDIT:我目前有:

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);
}

但是,这并不重要,我更希望海事委员会取得进展。

最佳回答

为了向遥远的计算机处理海事委员会的问题,你简单地指出,在/ManagementScope >>> 反对。

I m在C#中未见到,但这里有一个例子,即我使用MSDN和

<><>>(<>>Disapper:> 该法典未经测试。

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);
    }
}
问题回答

我也对此感到不安。 海事委员会可能会对班级和物体的方法产生误导。 我的解决办法是与C#和WMI一道在网络上重新设置一个东道国,但当地机器很容易简化:

private void rebootHost(string hostName)
{
    string adsiPath = string.Format(@"\{0}
ootcimv2", 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);
        }
    }
}

这将像药店那样工作。

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签