簡體   English   中英

C#PowerShell Get-Module

[英]C# PowerShell Get-Module

我正在嘗試為我們開發的某些Azure工作和自定義模塊創建一個“自定義” PowerShell外殼。 我想通過執行以下命令獲取模塊列表,但是outputCollection為空,並且DataAdded事件也不會觸發。

我到底在這里想念什么?

PS:是PowerShell 5,我使用了Nuget包Microsoft.PowerShell.5.ReferenceAssemblies

using System;
using System.Management.Automation;
using System.Threading;
namespace TestShell
{
    class Program
    {
        static void Main(string[] args)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript("Get-Module");

                PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
                outputCollection.DataAdded += outputCollection_DataAdded;
                PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded;
                IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Waiting for pipeline to finish...");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("Execution has stopped. The pipeline state: " + PowerShellInstance.InvocationStateInfo.State);
                foreach (PSObject outputItem in outputCollection)
                {
                    Console.WriteLine(outputItem.BaseObject.ToString());
                }
            }
        }

        static void outputCollection_DataAdded(object sender, DataAddedEventArgs e)
        {
            Console.WriteLine("Object added to output.");
        }

        static void Error_DataAdded(object sender, DataAddedEventArgs e)
        {
            Console.WriteLine("An error was written to the Error stream!");
        }
    }
}

將我的評論更改為答案:

添加-ListAvailable參數似乎對我-ListAvailable

PowerShellInstance.AddScript("Get-Module -ListAvailable");

由於我不明白的原因,即使$env:PsModulePath看起來正確,並且PowerShell -NoProfile仍然加載幾個模塊, Get-Module輸出為空,通過C#運行時,默認情況下似乎不加載任何模塊。

暫無
暫無

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

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