如何使用参数在c#中调用powershell脚本

如何使用参数在c#中调用powershell脚本,c#,powershell,C#,Powershell,我正在尝试使用c#中的参数调用powershell脚本。是否有任何选项只提供powershell脚本文件和参数,而不是在c#代码中以字符串形式提供整个powershell命令 快速的谷歌搜索真的能给你所需要的一切。这个是从 您需要参考System.Management.Automation 然后使用 创建运行空间以承载PowerScript环境: Runspace runSpace = RunspaceFactory.CreateRunspace(); runSpace.Open(); 使用运

我正在尝试使用c#中的参数调用powershell脚本。是否有任何选项只提供powershell脚本文件和参数,而不是在c#代码中以字符串形式提供整个powershell命令

快速的谷歌搜索真的能给你所需要的一切。这个是从

您需要参考
System.Management.Automation
然后使用

创建运行空间以承载PowerScript环境:

Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
使用运行空间,为cmdlet创建新管道:

Pipeline pipeline = runSpace.CreatePipeline();
创建命令对象以表示要执行的cmdlet,并将其添加到管道中。本例检索所有进程,然后根据它们的内存使用情况对它们进行排序

Command getProcess = new Command("Get-Process");
Command sort = new Command("Sort-Object");
sort.Parameters.Add("Property", "VM"); 
pipeline.Commands.Add(getProcess);
pipeline.Commands.Add(sort);
上述代码的功能与以下PowerShell命令行相同:

PS>Get进程|排序对象-属性VM

最后,执行管道中的命令,并对输出执行一些操作:

Collection output = pipeline.Invoke();
foreach (PSObject psObject in output)
{
  Process process = (Process)psObject.BaseObject;
  Console.WriteLine("Process name: " + process.ProcessName);
}

我上次做了类似这样的东西

public static string RunScript(string scriptText)
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(scriptText);
        pipeline.Commands.Add("Out-String");
        try
        {
            Collection<PSObject> results = pipeline.Invoke();
            runspace.Close();
            StringBuilder stringBuilder = new StringBuilder();
            if (pipeline.Error.Count > 0)
            {
                //iterate over Error PipeLine until end
                while (!pipeline.Error.EndOfPipeline)
                {
                    //read one PSObject off the pipeline
                    var value = pipeline.Error.Read() as PSObject;
                    if (value != null)
                    {
                        //get the ErrorRecord
                        var r = value.BaseObject as ErrorRecord;
                        if (r != null)
                        {
                            //build whatever kind of message your want
                            stringBuilder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
                            stringBuilder.AppendLine(r.InvocationInfo.PositionMessage);
                            stringBuilder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
                            stringBuilder.AppendLine(
                            string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
                        }
                    }
                }
            }
            else
                stringBuilder.AppendLine(string.Format("Build is Success"));
            return stringBuilder.ToString();
        }
        catch (Exception ex)
        {
            string err = ex.ToString();
            err = "Build Failed!!!" + "\r\n" + "Check the Setup File Available or Path error";
            return err;
        }
    }


 SCRIPT = "buildmsi.ps1 " + ssource + " " + sdestination;
            projectbuildstatus.Text = RunScript(SCRIPT);
publicstaticstringrunscript(stringscripttext)
{
Runspace Runspace=RunspaceFactory.CreateRunspace();
Open();
Pipeline Pipeline=runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add(“输出字符串”);
尝试
{
收集结果=pipeline.Invoke();
runspace.Close();
StringBuilder StringBuilder=新的StringBuilder();
如果(pipeline.Error.Count>0)
{
//迭代错误管道直到结束
而(!pipeline.Error.EndOfPipeline)
{
//从管道中读取一个PSObject
var value=pipeline.Error.Read()作为PSObject;
if(值!=null)
{
//获取错误记录
var r=value.BaseObject作为ErrorRecord;
如果(r!=null)
{
//建立你想要的任何类型的信息
stringBuilder.AppendLine(r.InvocationInfo.MyCommand.Name+“:”+r.Exception.Message);
stringBuilder.AppendLine(r.InvocationInfo.PositionMessage);
AppendLine(string.Format(“+CategoryInfo:{0}”,r.CategoryInfo));
stringBuilder.AppendLine(
格式(“+FullyQualifiedErrorId:{0}”,r.FullyQualifiedErrorId));
}
}
}
}
其他的
AppendLine(string.Format(“构建成功”);
返回stringBuilder.ToString();
}
捕获(例外情况除外)
{
字符串err=ex.ToString();
err=“生成失败!!!”+“\r\n”+“检查可用的安装文件或路径错误”;
返回错误;
}
}
SCRIPT=“buildmsi.ps1”+ssource+“”+s目标;
projectbuildstatus.Text=RunScript(脚本);

感谢Ale Tiro的想法

也许这篇文章和/或之前的问题可以帮助您?(注:因为您在问题中指定了C#我已经删除了VB.NET标记)我试图为.NET framework获取一些通用方法,而不是特定于C#
public static string RunScript(string scriptText)
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(scriptText);
        pipeline.Commands.Add("Out-String");
        try
        {
            Collection<PSObject> results = pipeline.Invoke();
            runspace.Close();
            StringBuilder stringBuilder = new StringBuilder();
            if (pipeline.Error.Count > 0)
            {
                //iterate over Error PipeLine until end
                while (!pipeline.Error.EndOfPipeline)
                {
                    //read one PSObject off the pipeline
                    var value = pipeline.Error.Read() as PSObject;
                    if (value != null)
                    {
                        //get the ErrorRecord
                        var r = value.BaseObject as ErrorRecord;
                        if (r != null)
                        {
                            //build whatever kind of message your want
                            stringBuilder.AppendLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message);
                            stringBuilder.AppendLine(r.InvocationInfo.PositionMessage);
                            stringBuilder.AppendLine(string.Format("+ CategoryInfo: {0}", r.CategoryInfo));
                            stringBuilder.AppendLine(
                            string.Format("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId));
                        }
                    }
                }
            }
            else
                stringBuilder.AppendLine(string.Format("Build is Success"));
            return stringBuilder.ToString();
        }
        catch (Exception ex)
        {
            string err = ex.ToString();
            err = "Build Failed!!!" + "\r\n" + "Check the Setup File Available or Path error";
            return err;
        }
    }


 SCRIPT = "buildmsi.ps1 " + ssource + " " + sdestination;
            projectbuildstatus.Text = RunScript(SCRIPT);