Powershell: String is added more than once to another string -
in script builds blob of text, there point block of "summary" text can prepended said blob.
although script generates summary text once, gets prepended text blob multiple times.
this powershell script:
# # test_textappend.ps1 # $reportmessage = "body of report able ere saw elba"; # build "report" text $fruitlist = [system.collections.arraylist]@(); $vegetablelist = [system.collections.arraylist]@(); [void]$fruitlist.add("apple"); # generate "summary" includes 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 found: {0}`n", $namelist); } if ($vegetablelist.count -gt 0) { $namearray = $vegetablelist.toarray([system.string]); $namelist = [string]::join(", ", $namearray); $sumtext.appendformat("the following vegetables found: {0}`n", $namelist); } if ($sumtext.length -gt 0) { $sumtext.append("`n"); } return ($sumtext.tostring()); } [string]$summary = (generatesummary); if (![string]::isnullorempty($summary)) # if there "summary" text, prepend { $reportmessage = $summary + $reportmessage; } write-output $reportmessage
and result when run:
the following fruits found: apple following fruits found: apple following fruits found: apple body of report able ere saw elba
i used code block instead of blockquote because fixed-width font shows leading spaces.
the question: why summary text repeated 3 times instead of once?
read about_return:
long description
the return keyword exits function, script, or script block. can used exit scope @ specific point, return value, or indicate end of scope has been reached.
users familiar languages c or c# might want use return keyword make logic of leaving scope explicit.
in windows powershell, the results of each statement returned output, without statement contains return keyword. languages c or c# return value or values specified return keyword.
results next 3 statements constitute output function:
$sumtext.appendformat("the following fruits found: {0}`n", $namelist); $sumtext.append("`n"); return ($sumtext.tostring());
(and next statement if $vegetablelist.count -gt 0
):
$sumtext.appendformat("the following vegetables found: {0}`n", $namelist);
Comments
Post a Comment