2009-06-23 95 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最有可能支持這種文件的絕對路徑或相對路徑。