抛出异常"安全错误"在调用powershell时

时间:2016-11-02 10:32:30

标签: c# .net powershell

调用powershell。

这是c#代码:

        using (PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(4, 0), null, null, false))
        {
            using (var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance))
            {
                runspace.Open();
                using (PowerShell powerShellInstance = PowerShell.Create())
                {
                    powerShellInstance.Runspace = runspace;
                    powerShellInstance.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted");
                    powerShellInstance.Invoke();
                    var pipeLineDetail = new PipeLineDetail();
                    var addParametersToScriptFile = new Command(scriptFile);
                    addParametersToScriptFile.Parameters.Add(new CommandParameter("Parameter", parameter));
                    var pipeline = powerShellInstance.Runspace.CreatePipeline();
                    pipeline.Invoke();
                    powerShellInstance.Dispose();
                }
            }
        }

上述代码在控制台应用程序中运行时工作正常,但在mvc应用程序中运行时抛出异常。

在运行行powerShellInstance.Invoke();异常时抛出如下:

消息:

  

安全错误。

     

Strack追踪:   在System.Management.Automation.Runspaces.AsyncResult.EndInvoke()   在System.Management.Automation.PowerShell.CoreInvokeRemoteHelper [TInput,TOutput](PSDataCollection`1输入,PSDataCollection`1输出,PSInvocationSettings设置)   在System.Management.Automation.PowerShell.CoreInvoke [TInput,TOutput](PSDataCollection`1输入,PSDataCollection`1输出,PSInvocationSettings设置)   在System.Management.Automation.PowerShell.CoreInvoke [TOutput](IEnumerable输入,PSDataCollection`1输出,PSInvocationSettings设置)   在System.Management.Automation.PowerShell.Invoke(IEnumerable输入,PSInvocationSettings设置)   在System.Management.Automation.PowerShell.Invoke()   在Syncfusion.Cluster.Manager.Base.Azure.AzureVmAutomation.CreateAzureVirtualMachines(String resourceGroupName,String location,Int32 numberOfDataNode,String vMUserName,String vMPassWord,String namenodeSize,String datanodeSize,String adUserName,String adPassWord,String powerShellScriptPath,String subscriptionId,String azureClusterPassword ,字符串logfilepath,String domainName,String azureImageVersion,Boolean reInstall)在e:\ svn \ datascience \ trunk \ AzureAutomation10 \ Base \ AzureVmAutomation.cs:第122行   在Syncfusion.Cluster.Manager.Controllers.AzureController。<> c__DisplayClass1b.b__f()在e:\ svn \ datascience \ trunk \ AzureAutomation10 \ Controllers \ AzureController.cs:第330行

1 个答案:

答案 0 :(得分:0)

设置默认执行政策enter image description here

  

要更改默认(LocalMachine)范围的执行策略,请使用"以管理员身份运行"启动Windows PowerShell。选项。

但是,根据您尝试执行的操作,您可以通过requires elevation参数设置策略的范围。可用值为:

CurrentUser
LOCALMACHINE
MachinePolicy
流程
UserPolicy