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

Hug*_*ugo 4 .net c# powershell web-services

我有以下代码,我测试和工作:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试将该函数包含在另一个项目中,以便从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.
Run Code Online (Sandbox Code Playgroud)

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

Sta*_*ing 8

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

要使其工作,您需要添加:

runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = System.Management.Automation.Runspaces.PSThreadOptions.UseCurrentThread;
Run Code Online (Sandbox Code Playgroud)

就在你打开运行空间之前.

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

希望这可以帮助,