C# 如何从用C编写的win表单运行powershell脚本#
首先,我有一些发展技能,但我已经很久没有使用它们了。 现在,我正在尝试自动安装服务器应用程序。 所以我想在这里做的是,我已经在谷歌上搜索了一段时间, 是打开一个Powershell脚本(我已经创建并添加到项目中)。 我已经添加了所有的代码,这样你就可以看到我哪里出错了。 脚本完成后,我需要if()来显示它是否正确完成 代码如下:C# 如何从用C编写的win表单运行powershell脚本#,c#,powershell,C#,Powershell,首先,我有一些发展技能,但我已经很久没有使用它们了。 现在,我正在尝试自动安装服务器应用程序。 所以我想在这里做的是,我已经在谷歌上搜索了一段时间, 是打开一个Powershell脚本(我已经创建并添加到项目中)。 我已经添加了所有的代码,这样你就可以看到我哪里出错了。 脚本完成后,我需要if()来显示它是否正确完成 代码如下: using System; using System.Collections.Generic; using System.ComponentModel;
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在这里有一个很棒的教程。添加参考:系统、管理、自动化 使用System.Collections.Objectmodel和 使用系统、管理、自动化
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());
}
}
}
使用(PowerShell PowerShellInstance=PowerShell.Create())
{
//使用“AddScript”将脚本文件的内容添加到执行管道的末尾。
//使用“AddCommand”将单个命令/cmdlet添加到执行管道的末尾。
AddScript(“param($urlPath)New Item-ItemType directory-Path\“$urlPath$d\”;”);
//使用“AddParameter”向管道上的最后一个命令/脚本添加单个参数。
PowerShellInstance.AddParameter(“urlPath”,@“D:\New PS Folder\”;
集合PSOutput=PowerShellInstance.Invoke();
//循环遍历每个输出对象项
foreach(PSOutput中的PSObject输出项)
{
//如果在脚本期间将null对象转储到管道中,则为null
//对象可能存在于此处。请检查null以防止潜在的NRE。
if(outputItem!=null)
{
//TODO:对输出项执行某些操作
//outputiItem.BaseOBject
Show(outputItem.Properties.ToString());
}
}
}
如果您的ps脚本已存档,或者您硬编码了它?我注意到您没有“使用system.management.automation”。我发现了这一点,但我仍然无法让powershell正常工作。我在其中使用了powershell,因此我添加和更改了一些内容。一些正常工作,一些不正常。我将关闭此线程,因为我提出的问题正在工作