【发布时间】:2012-02-29 11:20:56
【问题描述】:
我在我的应用程序中托管 powershell 并设置了一个受限的运行空间池,它基本上是空的(据我所知)。
public class MyPowerShell : IDisposable
{
private RunspacePool _runspacePool;
private PowerShell _shell;
public MyPowerShell()
{
try
{
var initialSessionState = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer);
_runspacePool = RunspaceFactory.CreateRunspacePool(initialSessionState);
_shell = PowerShell.Create();
_shell.RunspacePool = _runspacePool;
_shell.RunspacePool.Open();
_shell.AddCommand("Import-Module").AddParameter("Assembly", Assembly.GetExecutingAssembly());
_shell.Invoke();
_shell.Commands.Clear();
}
catch (Exception ex)
{
throw;
}
}
public void Dispose()
{
_shell.RunspacePool.Close();
_shell.Dispose();
}
public string[] Exec(string commandText)
{
var results = new List<string>();
try
{
_shell.AddScript(commandText);
foreach (var str in _shell.AddCommand("Out-String").Invoke<string>())
{
results.Add(str);
}
}
catch (Exception ex)
{
results.Add(ex.Message);
}
return results.ToArray();
}
}
显然,当我运行这段代码时...
_shell.AddCommand("Import-Module").AddParameter("Assembly", Assembly.GetExecutingAssembly());
_shell.Invoke();
_shell.Commands.Clear();
失败是因为没有可用的“Import-Module”cmdlet。所以,我的问题是如何在没有“Import-Module”cmdlet 的情况下导入模块?
这是我收到的错误消息...
“Import-Module”一词未被识别为 cmdlet 的名称, 函数、脚本文件或可运行的程序。检查拼写 名称,或者如果包含路径,请验证路径是否正确并 再试一次。
【问题讨论】:
-
x0n 的回答有帮助吗? stackoverflow.com/questions/6266108/…
-
它显示了导入模块的另一种方法,但我仍然收到相同的错误(我将使用实际的错误文本更新我的问题)。无论如何,谢谢。
-
只是一个愚蠢的问题,但您确实安装了 PS v2 对吗?您的代码是否适用于其他 cmdlet,例如
Get-Process? -
是的,我已经安装了 v2,我尝试创建一个正常的运行空间并执行“Get-Process”
标签: .net powershell powershell-2.0 cmdlets powershell-hosting