首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过PowerShell为多个远程主机并发执行C#脚本

通过PowerShell为多个远程主机并发执行C#脚本
EN

Stack Overflow用户
提问于 2022-08-10 09:10:26
回答 1查看 58关注 0票数 -1

我使用一个C#服务在不同的远程powershell主机上执行一些powershell命令。该服务可以并行连接到多个远程主机,并执行不同的powershell命令。

代码语言:javascript
复制
using (Runspace runspace = RunspaceFactory.CreateRunspace(this.GetConnectionInfo()))
{
  using (PowerShell powershell = PowerShell.Create())
    {
      powershell.Runspace = runspace;
      
      #Build up the powershell command

      powershell.Invoke();
    }
}

当我一次执行一个远程连接时,这很好。但是我注意到,当有多个远程连接并在多个线程中执行不同的命令时,powershell命令是针对错误的远程主机执行的,而不是在正确的远程主机上执行的。看起来,所有线程之间共享相同的运行空间,即使我在每个线程中创建了本地运行空间。

这里的问题应该是什么,以及针对不同powershell主机执行并行powershell命令的最佳实践是什么。

EN

回答 1

Stack Overflow用户

发布于 2022-08-10 10:03:13

我只能建议遵循微软的示例并使用RunspacePool

代码语言:javascript
复制
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.
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73303610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档