簡體   English   中英

從C#代碼調用PS腳本(Visual Studio 2017)

[英]Invoking PS script from C# code (Visual studio 2017)

我正在嘗試從C#代碼調用PS腳本。

**PS code. -- Try.ps1**
Write-Host "HelloHost"
Write-Debug "HelloDebug"
Write-Output "HelloOutput"
echo "tofile" > $PSScriptRoot/a.txt

**C# code**

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;

namespace TryitOut
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PowerShell pshell = PowerShell.Create())
            {
                string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                pshell.AddScript(path + "\\Try.ps1");
                IAsyncResult result = pshell.BeginInvoke();
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Waiting for PS script to finish...");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("Finished!");
                Console.ReadKey();
            }
        }
    }
}

當我獨立運行“ Try.ps1”時,它運行正常並創建a.txt,並且按預期顯示控制台輸出。 但是,它不會通過此C#代碼被調用/執行。 問題1 您能幫我個忙嗎? Q 2.通過C#代碼調用Try.ps1時,如何查看PS控制台輸出

感謝您的時間 :)。

處理PowerShell對象的輸出有兩種方法。 一個是Invoke調用的直接返回值,另一個是通過各種 在這兩種情況下,您都有責任處理數據。 當您在標准PowerShell窗口中運行腳本時,控制台不會自動輸出它們。 例如,要從Write-Object獲取結果,可以在while循環之后將以下內容添加到C#代碼中:

foreach(PSObject pso in pshell.EndInvoke(result))
{
   Console.WriteLine(pso);
}

這對於示例中的簡單字符串而言效果很好,但是對於具有多個屬性的復雜對象,則需要按名稱提取單個屬性。 例如:

string propValue = pso.Members["PropertyName"].Value.ToString();

看看我以前的答案,看看將復雜對象轉換為自己的類型的一種方法: 使用PowerShell Inside C#處理CimObjects

像這樣處理調試,信息,詳細信息等:

foreach(DebugRecord dbr in pshell.Streams.Debug)
{
   Console.WriteLine(dbr);
}

您還需要將其添加到腳本的開頭:

$DebugPreference = 'continue'

暫無
暫無

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

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