[英]How to run a powershell script from a win form written in C#
首先,我有一些开发技能,但是自从我使用它们已经很久了。 现在,我正在尝试自动化服务器应用程序的安装。 因此,我现在在这里进行了一段时间的搜索,就是打开一个Powershell脚本(我已经创建了该脚本,并将其添加到项目中。我已经添加了所有代码,以便您可以看到一旦脚本执行完毕,我需要if()向我显示脚本是否正确完成。
这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
//here i want to launch the powershell script
private void progressBar1_Click(object sender, EventArgs e)
{
if ( )
{
}
else {
MessageBox.Show("There is an error in the application or data", "Prerequisite",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
Application.Exit();
}
}
} }
我认为您需要使用“ PowerShellInstance.Invoke();”
Microsoft在这里有一个很棒的教程。 https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
添加参考: System.Management.Automation
使用System.Collections.Objectmodel和System.Management.Automation
using (PowerShell PowerShellInstance = PowerShell.Create())
{
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript("param($urlPath) New-Item -ItemType directory -Path \"$urlPath$d\";");
// use "AddParameter" to add a single parameter to the last command/script on the pipeline.
PowerShellInstance.AddParameter("urlPath", @"D:\New PS Folder\");
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
// loop through each output object item
foreach (PSObject outputItem in PSOutput)
{
// if null object was dumped to the pipeline during the script then a null
// object may be present here. check for null to prevent potential NRE.
if (outputItem != null)
{
//TODO: do something with the output item
// outputItem.BaseOBject
MessageBox.Show(outputItem.Properties.ToString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.