2

Exchange サーバーとの対話をActive Directory/Exchange使用して管理コンソールを構築することを計画しています。C#powershellDC

アプリケーションの起動時powershellにこれらのサーバーへの接続を確立し、それらを維持して、クエリやスクリプトなどを実行し続けることができるようにしたいのです。リモート接続を確立するのに数秒かかるためです。あなたがするすべてを遅らせる。

現在、ローカルの実行空間をテストしているだけですpowershellが、コマンドを送信するたびに終了し、最初のコマンドの後に再利用できません。

runspace何度も使用できるように、閉じないようにするにはどうすればよいですか?

編集: コード 非常に基本的で、実行空間を作成するだけで、後で基本的な機能がダウンしたときにモジュールを含めることができるようにする予定です。アイデアは、実行空間を作成し、powershell コードを実行する関数を呼び出すときに、その実行空間を別の変数に割り当てて再利用できるようにすることでしたが、私はおそらく愚かです。現在、ボタンをクリックしたときに送信されるダミーの「Get-Process」と、出力を表示するテキストボックスがあります。

public partial class MainWindow : Window
{
    Runspace powerShellRunspace = RunspaceFactory.CreateRunspace();
    public MainWindow()
    {

        InitializeComponent();
        powerShellRunspace.Open();
        string[] modules;
        scriptOutput.Text = "test";
        modules = new string[5];
        modules[0] = "john";



        //string result = powerShellRun("Get-Process");
        //powerShellInitialize(modules);

    }

    public static void powerShellInitialize(string[] modules)
    {
        Runspace powerShellRunspace = RunspaceFactory.CreateRunspace();
        powerShellRunspace.Open();

    }

    public string powerShellRun(string commands, Runspace powerShellRunspace)
    {

        Runspace powerShellRunspace2 = powerShellRunspace;
        Pipeline powerShellPipeline = powerShellRunspace2.CreatePipeline();
        powerShellPipeline.Commands.Add(commands);
        Collection<PSObject> powerShellResult = powerShellPipeline.Invoke();
        //string result="temp";
        //return result;
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in powerShellResult)
        {
            stringBuilder.AppendLine(obj.ToString());
        }

        return stringBuilder.ToString();

    }
}
4

1 に答える 1

1

この質問は、Keeping Powershell runspace open in .Netで既に回答されています。

要約すると、実行空間を開いたままにしておくことができますが、独立したクエリごとに、新しい Powershell インスタンスを作成する必要があります。

例:

Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();

//First Query
var firstQuery = PowerShell.Create();
firstQuery.Runspace = runspace;
firstQuery.AddScript("Write-Host 'hello'")

//Second Query
var secondQuery = PowerShell.Create();
secondQuery.Runspace = runspace;
secondQuery.AddScript("Write-Host 'world'")
于 2017-04-12T20:03:21.077 に答える