远程关闭计算机

Posted on 2019-01-22 14:17  努力成长静待花开  阅读(1058)  评论(0编辑  收藏  举报

实现代码:

  

知识运用:

  ConnectionOptions类  //指示生成WMI连接所需要的所有设置

    其Username  Passworr属性

  ManagementScope类  //表示管理操作的范围  (命名空间)

    public ManagementScope (string path , ConnectionOption  options)

    public void Connect()  //该方法用来将此ManagementScope连接到实际的WMI范围

实现代码:

        /// <summary>
        /// 关闭或重启远程计算机
        /// </summary>
        /// <param name="doinfo">执行的操作</param>
        public void CloseComputer(string doinfo)
        {
            ConnectionOptions co = new ConnectionOptions();                //创建ConnectionOptions对象
            co.Username =textBox2.Text;                                    //设置远程计算机用户名  
            co.Password = textBox3.Text;                                   //设置远程计算机登陆密码
            ManagementScope ms = new ManagementScope("\\\\" + textBox1.Text + "\\root\\cimv2:Win32_Service", co);
            try
            {
                ms.Connect();                                               //连接远程对象
                ObjectQuery obj1 = new ObjectQuery("select * from Win32_OperationSystem");  //创建ObjectQuery对象
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(obj1);     //创建ManagementObjectSearcher对象
                ManagementObjectCollection collection = searcher.Get();                     //得到WMI控制
                foreach(ManagementObject m in collection)
                {
                    string[] str = {""};
                    m.InvokeMethod(doinfo,str);
                }
            }
            catch (Exception et)
            {
                MessageBox.Show(et.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CloseComputer("Shutdown");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CloseComputer("Reboot");
        }