繁体   English   中英

PowerShell未定位到4.6

[英]PowerShell not targeting 4.6

我正在尝试使用.NET 4.6在C#中运行PowerShell脚本,我试图安装PowerShell NuGet,但它没有针对.NET 4.6,是否还有另一种方法可以执行PowerShell脚本?

我需要指定powershell.exe才能运行脚本。 但是现在我又遇到了一个问题,PowerShell窗口立即关闭,因此我看不到错误消息。 我正在使用以下命令

var s = Process.Start(@"Powershell.exe", $@"-noexit  -ExecutionPolicy Bypass -file ""MyScript.ps1; MyFunction"" ""{arguments}""");
s.WaitForExit();

是的,您可以在运行任何外部程序时运行它。 System.Diagnostics.Process将帮助您。

这是Microsoft社区的代码示例:

using System.Diagnostics;

namespace ConsoleApplication2
{
 class Program
 {
  static void Main(string[] args)
  {
   Process myProcess = new Process();

   myProcess.StartInfo.FileName = @"ConsoleApplication1.exe";
   myProcess.StartInfo.UseShellExecute = false;
   myProcess.StartInfo.RedirectStandardOutput = true;
   myProcess.StartInfo.RedirectStandardInput = true;

   myProcess.Start();

   string redirectedOutput=string.Empty;
   while ((redirectedOutput += (char)myProcess.StandardOutput.Read()) != "Enter File Name:") ;

   myProcess.StandardInput.WriteLine("passedFileName.txt");

   myProcess.WaitForExit();

   //verifying that the job was successfull or not?!
   Process.Start("explorer.exe", "passedFileName.txt");
  }
 }
}

ConsoleApplication1.exe应该替换为YourApplication.ps1

为什么您会使用System.Diagnostics.Process而不是建议的System.Management.Automation 因为powershell速度很慢,并且如果您需要更换它,那么使用System.Diagnostics.Process将允许立即进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM