简体   繁体   中英

Executing PowerShell script via C# for multiple remote hosts concurrently

I am using a C# service to execute some powershell commands in different remote powershell hosts. The service can connect to mutiple remote hosts in parallel and execute different powershell commands.

using (Runspace runspace = RunspaceFactory.CreateRunspace(this.GetConnectionInfo()))
{
  using (PowerShell powershell = PowerShell.Create())
    {
      powershell.Runspace = runspace;
      
      #Build up the powershell command

      powershell.Invoke();
    }
}

This works fine when I execute one remote connection at once. But I have noticed when having multiple remote connections and execute different commands in mutiple threads, powershell commands are executed against a wrong remote host, the command is not executed against the correct remote host. Looks like same runspace is shared among all threads even though I created local runspace inside each thread.

What should be the issue here and what are the best practices to execute parallel powershell commands agains different powershell hosts.

I can only suggest following Microsoft's example and using a RunspacePool .

namespace HostRunspacePool
{
  using System;
  using System.Collections.ObjectModel;
  using System.Management.Automation;
  using System.Management.Automation.Runspaces;

  /// <summary>
  /// This class provides the Main entry point for the Host application.
  /// </summary>
  internal class HostRunspacePool
  {
    /// <summary>
    /// This sample demonstrates the following.
    /// 1. Creating and opening a runspace pool.
    /// 2. Creating a PowerShell object.
    /// 3. Adding commands and arguments to the PowerShell object.
    /// 4. Running the commands asynchronously using the runspace
    ///    of the runspace pool.
    /// </summary>
    /// <param name="args">Parameter is not used.</param>
    private static void Main(string[] args)
    {
      // Create a pool of runspaces.
      using (RunspacePool rsp = RunspaceFactory.CreateRunspacePool())
      {
        rsp.Open();

        // Create a PowerShell object to run the following command.
        //  get-process wmi*
        PowerShell gpc = PowerShell.Create();
        // Specify the runspace to use and add commands.
        gpc.RunspacePool = rsp;
        gpc.AddCommand("Get-Process").AddArgument("wmi*");

        // Invoke the command asynchronously.
        IAsyncResult gpcAsyncResult = gpc.BeginInvoke();
        // Get the results of running the command.
        PSDataCollection<PSObject> gpcOutput = gpc.EndInvoke(gpcAsyncResult);

        // Process the output.
        Console.WriteLine("The output from running the command: get-process wmi*");
        for (int i= 0; i < gpcOutput.Count; i++)
        {
         Console.WriteLine(
                           "Process Name: {0} Process Id: {1}",
                           gpcOutput[i].Properties["ProcessName"].Value,
                           gpcOutput[i].Properties["Id"].Value);
        }
      } // End using.
    } // End Main entry point.
  } // End HostPs5 class.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM