0
在構建一個文本塊的腳本中,有一點可以將一個「摘要」文本塊預先添加到所述blob中。Powershell:字符串被多次添加到另一個字符串
儘管腳本只生成一次摘要文本,但它多次被預置爲文本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
我使用的代碼塊,而不是塊引用因爲固定寬度的字體示出了額外的領先空間。
問題:爲什麼摘要文本重複三次而不是一次?
這是一個微妙但重要的區別在於直到現在我還沒有考慮過。調用StringBuilder實例的Append方法將返回StringBuilder的內容。將'[void]'放在每個語句的前面確保只返回對ToString()的調用結果。 – user1956801