In a script that builds a blob of text, there is a point where a block of "summary" text can be prepended to said blob.
Although the script only generates the summary text once, it gets prepended to the text blob multiple times.
This is the PowerShell script:
#
# 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
And this is the result when it is run:
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
I used a code block instead of blockquote because the fixed-width font shows the extra leading spaces.
The question: why does the summary text get repeated three times instead of only once?
Read about_Return:
LONG DESCRIPTION
The Return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.
Users who are familiar with languages like C or C# might want to use the Return keyword to make the logic of leaving a scope explicit.
In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the Return keyword.
Results from all next three statements constitute output from your function:
$sumText.AppendFormat("The following fruits were found: {0}`n", $nameList);
$sumText.Append("`n");
return ($sumText.ToString());
(and from next statement as well if $vegetableList.Count -gt 0
):
$sumText.AppendFormat("The following vegetables were found: {0}`n", $nameList);