2009-06-23 61 views
0

我想知道如何使用RunspaceConfiguration.Create()方法调用。我想设置C#的托管方式,通过确保所有Cmdlet,提供程序等都可用,从而通过c#执行任何可以想象的PowerShell脚本。看看PowerShell样本,样本5,它有以下几点。c#Powershell。使用RunspaceConfiguration.Create配置运行空间

RunspaceConfiguration config = RunspaceConfiguration.Create("SampleConsole.psc1", out warnings); 

.psc1如何被创建,或从哪里存储,检索。任何帮助,将不胜感激。

回答

3

我不得不做一些邪恶 hackery得到这个发生 - 你可以在评论中看到它,但基本上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; 
    } 
} 
+0

干杯。 修复了我甚至不知道的一个问题。谢谢。鲍勃。 – 2009-06-23 19:36:50

2

.psc1文件可以与Export-Console小命令被创建。通常,您可以使用所需的管理单元设置控制台环境,然后导出其配置。

RunspaceConfiguration.Create最有可能支持这种文件的绝对路径或相对路径。

相关问题