[英]Import PowerShell Module from C# Failing
I have seen quite a number of solutions, but none addresses my problem. 我见过很多解决方案,但都没有解决我的问题。 I am trying to import a custom PowerShell module called "DSInternals" to my C# DLL. 我正在尝试将名为“DSInternals”的自定义PowerShell模块导入到我的C#DLL中。
https://github.com/MichaelGrafnetter/DSInternals https://github.com/MichaelGrafnetter/DSInternals
Everything in my code seems just fine, but when I try to get the available module it's not loaded. 我的代码中的所有内容似乎都很好,但是当我尝试获取可用模块时,它没有加载。
The stream responds with 流响应
The term 'Get-ADReplAccount' is not recognized as the name of a cmdlet, function, script file, or operable program. 术语“Get-ADReplAccount”未被识别为cmdlet,函数,脚本文件或可操作程序的名称。 Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
Where Am I going wrong with this code? 这个代码我哪里错了?
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
}
The issue was the .NET framework version in which the module was built in. Adding a module which was built with a higher version of the .NET framework to the C# class will not work. 问题是构建模块的.NET框架版本。将使用更高版本的.NET框架构建的模块添加到C#类将不起作用。 The module was built in 4.5.1 and I was working with version 2, adding 该模块是在4.5.1中构建的,我正在使用版本2,添加
init.ThrowOnRunspaceOpenError=true;
Helped in catching the cause of the error. 帮助抓住错误的原因。
Here is my final code that works 这是我的最终代码
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.