Powershell:String被多次添加到另一个字符串

时间:2016-09-13 00:07:51

标签: string powershell stringbuilder string-concatenation

在构建一个文本blob的脚本中,有一个点是" summary"文本可以预先添加到所述blob中。

虽然脚本只生成一次摘要文本,但它会多次添加到文本blob中。

这是PowerShell脚本:

#
# Test_TextAppend.ps1
#

$reportMessage = "Body of Report Able Was I Ere I Saw Elba";   # build "report" text

$fruitList = [System.Collections.ArrayList]@();
$vegetableList = [System.Collections.ArrayList]@();

[void]$fruitList.Add("apple");

# Generate a "summary" that includes the contents of both lists
function GenerateSummary()
{
    [System.Text.StringBuilder]$sumText = New-Object ("System.Text.StringBuilder")
    $nameArray = $null;
    [string]$nameList = $null;

    if ($fruitList.Count -gt 0)
    {
        $nameArray = $fruitList.ToArray([System.String]);
        $nameList = [string]::Join(", ", $nameArray);
        $sumText.AppendFormat("The following fruits were found: {0}`n",
            $nameList);
    }

    if ($vegetableList.Count -gt 0)
    {
        $nameArray = $vegetableList.ToArray([System.String]);
        $nameList = [string]::Join(", ", $nameArray);
        $sumText.AppendFormat("The following vegetables were found: {0}`n",
            $nameList);
    }

    if ($sumText.Length -gt 0)
    {
        $sumText.Append("`n");
    }

    return ($sumText.ToString());
}

[string]$summary = (GenerateSummary);

if (![string]::IsNullOrEmpty($summary))    # if there is any "summary" text, prepend it
{
    $reportMessage = $summary + $reportMessage;
}

Write-Output $reportMessage

这是运行时的结果:

The following fruits were found: apple

 The following fruits were found: apple

 The following fruits were found: apple

Body of Report Able Was I Ere I Saw Elba

我使用了代码块而不是blockquote,因为固定宽度字体显示了额外的前导空格。

问题:为什么摘要文本重复三次而不是一次?

1 个答案:

答案 0 :(得分:3)

阅读about_Return

  

详细说明

     

Return关键字退出函数,脚本或脚本块。它   可用于退出特定点的范围,以返回a   值,或表示已达到范围的结尾。

     

熟悉C或C#等语言的用户可能希望这样做   使用Return关键字来制作离开范围的逻辑   明确的。

     

在Windows PowerShell中,返回每个语句的结果   作为输出,即使没有包含Return的语句   关键词。 C或C#等语言仅返回一个或多个值   由Return关键字指定。

以下三个语句的结果构成了函数的输出:

    $sumText.AppendFormat("The following fruits were found: {0}`n", $nameList); 

    $sumText.Append("`n");

return ($sumText.ToString());

(以及$vegetableList.Count -gt 0时的下一个陈述):

$sumText.AppendFormat("The following vegetables were found: {0}`n", $nameList);