C#system.management.automation.dll不会将powershell.exe作为新系统进程启动

时间:2016-10-20 12:19:09

标签: c# powershell azure-powershell

我使用过c#应用程序的Azure powershell。我已经尝试过system.management.automation.dll,如下所示

 string scriptPath = @"Microsoft_Image\loadjsontemplate"+i+".ps1";
                var addParametersToScriptFile = new Command(scriptPath);
                addParametersToScriptFile.Parameters.Add(new CommandParameter("AdUsername", resourceGroup.AdUsername));
                addParametersToScriptFile.Parameters.Add(new CommandParameter("AdPassword", resourceGroup.AdPassword));
                addParametersToScriptFile.Parameters.Add(new CommandParameter("SubscriptionId",resourceGroup.SubscriptionId));
                addParametersToScriptFile.Parameters.Add(new CommandParameter("ResourceGroupName", "testcloud1"+i));
                addParametersToScriptFile.Parameters.Add(new CommandParameter("LocationName", "eastus2"));
                var runspace = RunspaceFactory.CreateRunspace();
                runspace.Open();

                var powerShell = PowerShell.Create();

                var scriptInvoker = new RunspaceInvoke(runspace);

                scriptInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned");
                powerShell.Runspace = runspace;
                var pipeline = powerShell.Runspace.CreatePipeline();
                pipeline.Commands.Add(addParametersToScriptFile);
                pipeline.Invoke();
                pipeline.Dispose();
                runspace.Close();
                runspace.Dispose();
                powerShell.Dispose();

以上代码不会创建新进程。如果我使用多线程,那么所有的运行空间都在同一个进程中启动。但是当我使用system.diagnostics.process时,它会将每个请求作为单个进程启动。

 string argument = " -ExecutionPolicy ByPass & {& \"D:\\TestingIIS\\Testingparallel\\Testingparallel\\Microsoft_Image\\loadjsontemplate0.ps1\" -ResourceGroupName testcloud2" + i + " -LocationName westus -AdPassword " + resourceGroup.AdPassword + " -AdUserName " + resourceGroup.AdUsername + " -SubscriptionId " + resourceGroup.SubscriptionId + "}";
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = "powershell.exe";
                psi.Arguments = argument;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError = true;
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                Process process = new Process();
                process.StartInfo = psi;
                process.Start();
                Console.WriteLine(process.StandardOutput.ReadToEnd());
               Console.WriteLine(process.StandardError.ReadToEnd());

system.management.automation.dll与system.diagnostics.process之间有什么不同? 如何在system.management.automation.dll中启动单独的powershell.exe进程?

0 个答案:

没有答案