创建运行空间失败

本文关键字:失败 空间 运行 创建 | 更新日期: 2023-09-27 18:33:40

问题:

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

安装:

  • Windows PowerShell
  • Windows PowerShell (x86)
  • Windows PowerShell ISE
  • Windows PowerShell ISE (x86)
  • Windows PowerShell Modules

例外:

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 4.0(从Powerershell 3.0)解决

http://social.technet.microsoft.com/wiki/contents/articles/21016.how-to-install-windows-powershell-4-0.aspx