错误执行使用C#PowerShell的命令行开关 [英] Error executing Powershell commandlets using C#

查看:724
本文介绍了错误执行使用C#PowerShell的命令行开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我已经测试和工程以下code:

I have the following code that I have tested and works:

    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:

However, when I try to include the function in a different project so that it is called from a webservice it throws an 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.

我不知道为什么会这样。任何帮助将是AP preciated。

I have no idea why this is happening. Any help would be appreciated.

推荐答案

这是怎么回事的是,冒领只假冒的线程上,和PowerShell的运行空间是另一个线程上运行。

What's happening is that Impersonator only impersonates on the thread, and PowerShell's Runspace is running on another thread.

要完成这项工作,你需要添加:

To make this work, you need to add:

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

您打开运行空间之前。

这将迫使运行空间在同一个线程中模拟的令牌运行。

This will force the runspace to run on the same thread as the impersonated token.

希望这有助于

这篇关于错误执行使用C#PowerShell的命令行开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆