C# PowerShell不以4.6为目标
我正在尝试使用.NET4.6在C#中运行PowerShell脚本 我已尝试安装PowerShell NuGet,但它不针对.NET 4.6 是否有其他方法可以执行PowerShell脚本 我需要指定powershell.exe才能运行脚本。但现在我遇到另一个问题,PowerShell窗口立即关闭,因此我无法看到错误消息。我正在使用以下命令C# PowerShell不以4.6为目标,c#,.net,powershell,C#,.net,Powershell,我正在尝试使用.NET4.6在C#中运行PowerShell脚本 我已尝试安装PowerShell NuGet,但它不针对.NET 4.6 是否有其他方法可以执行PowerShell脚本 我需要指定powershell.exe才能运行脚本。但现在我遇到另一个问题,PowerShell窗口立即关闭,因此我无法看到错误消息。我正在使用以下命令 var s = Process.Start(@"Powershell.exe", $@"-noexit -ExecutionPolicy Bypass -f
var s = Process.Start(@"Powershell.exe", $@"-noexit -ExecutionPolicy Bypass -file ""MyScript.ps1; MyFunction"" ""{arguments}""");
s.WaitForExit();
是的,您可以像运行任何外部程序一样运行它<代码>系统.诊断.过程将帮助您解决问题 以下是一个代码示例:
ConsoleApplication1.exe
应替换为YourApplication.ps1
为什么您会使用
System.Diagnostics.Process
而不是System.Management.Automation
?因为powershell速度很慢,如果您需要更换它,使用System.Diagnostics.Process
将允许立即执行此操作。您可以添加一些您正在使用的代码吗?您好@DanSchnau查看更新的代码…@doorman powershell在.NET 4.6中工作。你尝试了什么?问题是什么?如果你说的是真的,没有人能够使用它-4.6是所有以前的4.x版本的二进制替代品。嗨@PanagiotisKanavos基本上我尝试添加Powershell Nuget软件包,但它不会安装。抱怨它不是4的目标。6@doorman作者是一个随机的家伙,该软件包没有下载,甚至2013年的非官方软件包也有40万次下载。为什么不试试Powershell上的几十个教程中的一个,例如MSDN?嗨,Mindaugas,谢谢你的帮助。我更新了我的问题,您知道如何防止powershell窗口关闭,或者如何获取脚本中发生的错误吗?如果问题出现在powershell代码中,请自行运行脚本,而无需调用代码。要查看输出/错误消息,只需从Powershell shell调用它。运行>poershell>浏览scipt目录>运行该Powershell脚本。它将打印出错误。嗨,Mindaugas,当我从powershell调用它时,就像这样的powershell-executionPolicy bypass-noexit-file“myproject.ps1 myfunction”,它抱怨该文件没有.ps1扩展名。这是在ps文件中触发函数的正确方法吗?没有理由使用Process.Start,因为您可以在.NET.Hi@PanagiotisKanavos中创建Powershell管道。您能给出一个使用.NET 4.6的示例吗?
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");
}
}
}