使用C#执行Powershell命令行开关时出错

时间:2011-07-04 06:45:20

标签: c# .net web-services powershell

我已经测试并运行了以下代码:

    using (new Impersonator("Administrator", "dev.dev", #########"))
    {
        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

        runspace.Open();

        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

        Pipeline pipeline = runspace.CreatePipeline();
        Command myCmd = new Command(@"C:\test.ps1");
        myCmd.Parameters.Add(new CommandParameter("upn", upn));
        myCmd.Parameters.Add(new CommandParameter("sipAddress", sipAddress));
        pipeline.Commands.Add(myCmd);

        // Execute PowerShell script
        Collection<PSObject> results = pipeline.Invoke();
    }

但是,当我尝试将该函数包含在另一个项目中,以便从Web服务调用它时会抛出一个execption:

    System.Management.Automation.CmdletInvocationException: Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. ---> System.UnauthorizedAccessException: Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.

我不知道为什么会这样。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:8)

发生的事情是Impersonator只模仿线程,而PowerShell的Runspace正在另一个线程上运行。

要使这项工作,您需要添加:

runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = System.Management.Automation.Runspaces.PSThreadOptions.UseCurrentThread;

在打开运行空间之前。

这将强制运行空间在与模拟令牌相同的线程上运行。

希望这有帮助,

答案 1 :(得分:1)

使用这些名称空间:

using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;

使用InitialSessionState创建运行空间

InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ApartmentState = ApartmentState.STA;
initialSessionState.ThreadOptions = PSThreadOptions.UseCurrentThread;

using ( Runspace runspace = RunspaceFactory.CreateRunspace ( initialSessionState ) )
{
  runspace.Open();

  // scripts invocation                 

  runspace.Close();
}