簡體   English   中英

從 powershell 捕獲 output 沒有 PowerShell object

[英]Capture output from powershell without The PowerShell object

在我的 c# 應用程序中有一些按鈕,當用戶單擊此按鈕時,應用程序運行 powershell 腳本。

powershell 的 window 彈出,用戶在電源 shell window 中看到結果。

我正在嘗試從 powershell window 中獲取 output 並在我的應用程序的某些文本框中顯示 output。

這是我的代碼:

int ExecuteScript(string path)
        {
            // this is the script that i would run in a process and would monitor. You don't need to put anything
            // in the script just put it to sleep for like 1 minute or so.
            string command; 
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            command = "$job = [Diagnostics.Process]::Start(\"powershell.exe\", \"" + path + "\")"; // * if $null is passed it needs to be '$null' *
            scriptInvoker.Invoke(command);

            int pid = 0;
            foreach (PSObject result in scriptInvoker.Invoke("$job.id"))
            {
                if (result != null)
                {

                    pid = Convert.ToInt32(result.ToString());
                }
            }
            return pid;

        }

對於某些版本問題,我沒有使用PowerShell object 來運行腳本

當您調用 Powershell.exe 時,您可以包含“-windowstyle hidden”,powershell 應該在后台運行。

暫無
暫無

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

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