![](/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.