簡體   English   中英

從C#導入PowerShell模塊失敗

[英]Import PowerShell Module from C# Failing

我見過很多解決方案,但都沒有解決我的問題。 我正在嘗試將名為“DSInternals”的自定義PowerShell模塊導入到我的C#DLL中。

https://github.com/MichaelGrafnetter/DSInternals

我的代碼中的所有內容似乎都很好,但是當我嘗試獲取可用模塊時,它沒有加載。

流響應

術語“Get-ADReplAccount”未被識別為cmdlet,函數,腳本文件或可操作程序的名稱。 檢查名稱的拼寫,或者如果包含路徑,請驗證路徑是否正確,然后重試。

這個代碼我哪里錯了?

InitialSessionState init = InitialSessionState.CreateDefault();
init.ImportPSModule(new string[] { @"D:\\DSInternals\\dsinternals.psd1" }); //location of the module files
Runspace runspace = RunspaceFactory.CreateRunspace(init);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-ADReplAccount"); //this command is un-recognized

foreach (PSObject result in ps.Invoke())
{
    Console.WriteLine(result); //this always returns null
}

問題是構建模塊的.NET框架版本。將使用更高版本的.NET框架構建的模塊添加到C#類將不起作用。 該模塊是在4.5.1中構建的,我正在使用版本2,添加

init.ThrowOnRunspaceOpenError=true;

幫助抓住錯誤的原因。

這是我的最終代碼

        InitialSessionState init = InitialSessionState.CreateDefault();
        init.ImportPSModule(new string[] { @"D:\\DSInternals\\dsinternals.psd1" }); //location of the module files
        init.ThrowOnRunspaceOpenError = true;
        Runspace runspace = RunspaceFactory.CreateRunspace(init);
        runspace.Open();
        var script =
            "Get-ADReplAccount -SamAccountName peter -Domain BLABLA -Server dc.BLABLA.co.za -Credential $cred -Protocol TCP"; //my powershell script

        _powershell = PowerShell.Create().AddScript(script);
        _powershell.Runspace = runspace;

        var results = _powershell.Invoke();
        foreach (var errorRecord in _powershell.Streams.Progress)
            Console.WriteLine(errorRecord);
        foreach (var errorRecord in _powershell.Streams.Debug)
            Console.WriteLine(errorRecord);
        foreach (var errorRecord in _powershell.Streams.Error)
            Console.WriteLine(errorRecord);
        foreach (var errorRecord in _powershell.Streams.Warning)
            Console.WriteLine(errorRecord);

        var stringBuilder = new StringBuilder();
        foreach (var obj in results)
        {
            stringBuilder.AppendLine(obj.ToString());
        }

        return stringBuilder.ToString();

暫無
暫無

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

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