![](/img/trans.png)
[英]Create Remote Powershell Session and load modules in Runspace using C#
[英]c# Powershell. Configure runspace using RunspaceConfiguration.Create
我试图找出如何使用RunspaceConfiguration.Create()
方法调用。 我想通过确保所有Cmdlet,Providers等都可用的方式来设置c#主机,以使其能够从c#执行任何可能的powershell脚本。 查看powershell示例(示例5),它具有以下内容。
RunspaceConfiguration config = RunspaceConfiguration.Create("SampleConsole.psc1", out warnings);
.psc1是如何创建的,或从哪里检索的。 任何帮助,将不胜感激。
我不得不做一些邪恶的两轮牛车让这样的事情发生-你可以在评论读它,但基本上PS不能做到这一点目前。
var _currentRunspace = RunspaceFactory.CreateRunspace(this);
/* XXX: We need to enable dot-sourcing - unfortunately there is no
* way in code to just enable it in our host, it always goes out to
* the system-wide settings. So instead, we're installing our own
* dummy Auth manager. And since PSh makes us reimplement a ton of
* code to make a custom RunspaceConfiguration that can't even properly
* be done because we only have the public interface, I'm using
* Reflection to hack in the AuthManager into a private field.
* This will most likely come back to haunt me. */
var t = typeof(RunspaceConfiguration);
var f = t.GetField("_authorizationManager", BindingFlags.Instance | BindingFlags.NonPublic);
f.SetValue(_currentRunspace.RunspaceConfiguration, new DummyAuthorizationManager());
_currentRunspace.Open();
return _currentRunspace;
public class DummyAuthorizationManager : AuthorizationManager
{
const string constshellId = "Microsoft.PowerShell";
public DummyAuthorizationManager() : this (constshellId) {}
public DummyAuthorizationManager(string shellId) : base(shellId) {}
protected override bool ShouldRun(CommandInfo commandInfo, CommandOrigin origin, PSHost host, out Exception reason)
{
// Looks good to me!
reason = null;
return true;
}
}
可以使用Export-Console
cmdlet创建.psc1
文件。 通常,您将使用所需的管理单元设置控制台环境,然后导出其配置。
RunspaceConfiguration.Create
很可能支持此类文件的绝对或相对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.