Use WMI to Run Commands on Remote Machine

It is very common that you need to run some commands on a remote server. For example, you may want to config your source control server to start a build process on a dedicated build machine once it receives any checkins. To achieve this, you can leverage the WMI scripting APIs.

The steps are:

  1. Use SWbemLocator to create Locator object
  2. Use the Locator object to connect to the remote server and get back a Service object
  3. Use the Service object to get a Win32 process object
  4. Finally, use the Process object to issue your command

WMI WbemScripting script sample:

    Function RemoteExecute(strServer, strUser, strPassword, CmdLine)
        Const Impersonate = 3

        RemoteExecute = -1
        
        Set Locator = CreateObject("WbemScripting.SWbemLocator")
        Set Service = Locator.ConnectServer(strServer, "root\cimv2", strUser, strPassword)
      
        Service.Security_.ImpersonationLevel = Impersonate 
        Set Process = Service.Get("Win32_Process")
        
        result = Process.Create(CmdLine, , , ProcessId)

        If (result <> 0) Then
            WScript.Echo "Creating Remote Process Failed: " & result
            Wscript.Quit
        End If

        RemoteExecute = ProcessId
    End Function

NAnt is very popular in the .Net development community. You may want to write a C# extension for NAnt scripts to achieve some build automations on remote servers. You can achieve that easily too. I am posting a WMI C# sample below for your reference too.

WMI C# sample:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Management;

    namespace WMISample
    {
        class Program
        {
            static void Main(string[] args)
            {
                string remoteMachine = "localhost";

                ConnectionOptions connOptions = new ConnectionOptions();
                connOptions.Impersonation = ImpersonationLevel.Impersonate;
                connOptions.EnablePrivileges = true;

                ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", remoteMachine), connOptions);
                manScope.Connect();

                ObjectGetOptions objectGetOptions = new ObjectGetOptions();
                ManagementPath managementPath = new ManagementPath("Win32_Process");
                ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);

                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

                inParams["CommandLine"] = @"notepad.exe";
                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                Console.WriteLine("Creation of the process returned: " + outParams["returnValue"]);
                Console.WriteLine("Process ID: " + outParams["processId"]);
                Console.ReadLine();
            }
        }
    }

See also

  • SQL: Use Dynamic SQL Query Correctly
  • SQL 2005: Use DMV and CROSS APPLY to Get Cached Plans
  • SQL 2005: Discontinued or Deprecated Features in SQL Server 2005
  • SQL 2005: Default Trace Enabled Option
  • SQL 2005: Column Level Permissions
  • SQL 2005: SQLCMD Supports Parameterized Variables and Macro Features
  • SQL 2005: DTS Has Become SSIS now
  • SQL 2005: Microsoft SQL Server 2005 JDBC Driver
  • SQL 2005: Query Notifications in ADO.Net 2.0
  • SQL 2005: Overcome SQL Index Size Limit
  • SQL 2005: DDL Triggers
  • SQL 2005: Why Should Use 64 Bit Now
  • SQL 2005: How to Rebuild The Master Database
  • SQL 2005: A Little Trick to Install SQL 2005 Onto Your Dirty DEV Machine
  • SQL 2005: New Resource Database
  • SQL 2005: Alter Index Rebuild
  • SQL 2005: XQuery Sample
  • SQL 2005: How to Move Database
  • SQL: Use COALESCE to Generate a List
  • SQL: How to Debug SQL Deadlocks
  • .Net: How to Bypass Strong Name Check
  • Agile: Lean Software Development - An Agile Toolkit
  • ORM: How to Use nHibernate 1.2 to Call Stored Procedure to Return a Dataset Without a Mapping Entity
  • AJAX: ASP.NET AJAX Tips
  • .Net: Debugging Commands
  • .Net: How to Run NUnit And Debug Your Test Fixtures Directly from VS 2005
  • .Net: How to Add Domain User to Local Group
  • .Net: Lock Value Type?
  • .Net: How to Create an Instance of a Generic Type with Parameters
  • .Net: How to Get Address of a Managed Type
  • ORM: New Features of nHibernate 1.2
  • .Net: How to Get System Error Message from HRESULT in Managed Code
  • .Net: Use Windows PowerShell Now
  • WMI: Use WMI to Run Commands on Remote Machine
  • API: GetLogicalProcessorInformation to Detect CPUs
  • .Net: How to Implement Singleton Correctly
  • .Net: There is no MTS object context (Exception from HRESULT: 0x8004E004)
  • .Net: The Net Objectives Pattern Repository
  • Web: Access Denied When ASP.Net Accesses Eventlog
  • Nant: Error Loading GUID of Project
  • AJAX: Ajax in Action
  • DTC: DtcGetTransactionManager Fails
  • .Net: Run .Net 1.1 COM+ Serviced Components Under .Net 2.0 Framework
  • .Net: Debugging Managed Code Tip
  • .Net: Assembly Binding Log Viewer (Fuslogvw.exe)
  • .Net: .Net Framework Design Guidelines
  • .Net: Use Global Catalog and CheckTokenMembership to Check AD Group Membership



  • THIS POST IS PROVIDED "AS-IS" WITH NO WARRANTIES AND CONFERS NO RIGHTS. Build time: Sun 03/30/2008 . ©2007 Dalun Software. All rights reserved. Back to Article List