簡體   English   中英

在C#WPF中保持Powershell運行空間正常運行?

[英]Keeping a powershell runspace alive in C# WPF?

我正計划使用C# powershellDC和Exchange服務器進行通訊來構建Active Directory/Exchange管理控制台。

我想在應用程序啟動時建立與這些服務器的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();

    }
}

關於在.Net中保持Powershell運行空間打開的問題,已經回答了。

總而言之,您可以使Runspace保持打開狀態,但是對於每個獨立的查詢,您都需要創建一個新的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'")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM