创建运行空间失败

时间:2014-12-09 17:52:59

标签: c# powershell exception

问题:

您好,我想在c#程序中使用powershell。 我尝试了一些来自Web和这里的示例,但它们都无法使用InvalidProgramException创建运行空间。 Powershell安装在我的机器上(Windows7 64bit),当我从开始菜单启动它时我可以使用它(我假设安装了x86和x64,这可能是问题)

已安装的:

  • Windows PowerShell
  • Windows PowerShell(x86)
  • Windows PowerShell ISE
  • Windows PowerShell ISE(x86)
  • Windows PowerShell模块

例外:

Ein Ausnahmefehler des Typs "System.InvalidProgramException" ist in PowerShellExecutionSample.exe aufgetreten.

   bei System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()
   bei PowerShellExecutionSample.PowerShellRunner.Run(IDictionary`2 parameters, String script) in c:\Temp\0601.PowerShellExecutionSample\PowerShellExecutionSample\PowerShellRunner.cs:Zeile 26.
   bei PowerShellExecutionSample.Program.Main(String[] args) in c:\Temp\0601.PowerShellExecutionSample\PowerShellExecutionSample\Program.cs:Zeile 20.
   bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)

代码:

public void Run(string script, IDictionary<string, object> parameters = null)
{
    using (Runspace runSpace = RunspaceFactory.CreateRunspace())
    {
        runSpace.Open();

        using (Pipeline pipeline = runSpace.CreatePipeline())
        {
            // In-vars
            if (parameters != null)
            {
                foreach (var param in parameters)
                {
                    runSpace.SessionStateProxy.SetVariable(param.Key, param.Value);
                }
            }

            // execute
            pipeline.Commands.AddScript(script);
            Collection<PSObject> results = pipeline.Invoke();

            // Out-vars
            if (parameters != null)
            {
                foreach (var param in parameters)
                {
                    parameters[param.Key] = runSpace.SessionStateProxy.PSVariable.GetValue(param.Key);
                }
            }
        }

        runSpace.Close();
    }
} 

问题:

为什么会失败?我的程序是否尝试实例化错误的运行空间(x86 v.x64)?我是否需要安装PowerShell的特殊版本或设置一些权限?

1 个答案:

答案 0 :(得分:0)

相关问题