C#,如何在foreach循环中将字符串拆分为新行?

时间:2013-11-12 21:21:54

标签: c# asp.net powershell

使用Powershell对象并运行foreach循环来获取结果,

我得到2个正确的IP地址结果144.68.205.19和144.68.205.22但是它打印在1行,

144.68.205.19144.68.205.22

它被认为是像这样拆分新行,

144.68.205.19
144.68.205.22

请告知,这里是C#代码,

// Powershell
            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.Open();
            Pipeline pipeline = runSpace.CreatePipeline();

            Command invokeScript = new Command("Invoke-Command");
            RunspaceInvoke invoke = new RunspaceInvoke();

            // invoke-command -computername compName -scriptblock { get-process }

            ScriptBlock sb = invoke.Invoke("{"+ PowerShellCodeBox.Text +"}")[0].BaseObject as ScriptBlock;
            invokeScript.Parameters.Add("scriptBlock", sb);
            invokeScript.Parameters.Add("computername", TextBoxServer.Text);

    string str = "";

    pipeline.Commands.Add(invokeScript);
    Collection<PSObject> output = pipeline.Invoke();
    foreach (PSObject psObject in output)
    {

        str = str + psObject;
    }

    if (str == ""){
        str = "Error";

        ResultBox.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
    }

    ResultBox.Text = str;

2 个答案:

答案 0 :(得分:2)

您可以在构建str时插入新行:

foreach (PSObject psObject in output)
{
    str += "\n" + psObject;
}

或使用string.Join

string str = String.Join("\n", output);

答案 1 :(得分:1)

对于初学者,如果您计划在循环中构建字符串,请查看使用StringBuilder。其次,你永远不会在那里添加新的一行,但这很容易解决(使用本地的stringbuilder方法!)

pipeline.Commands.Add(invokeScript);
Collection<PSObject> output = pipeline.Invoke();

StringBuilder sb = new StringBuilder();
foreach (PSObject psObject in output)
{
    sb.AppendLine(psObject.ToString());
}