Dans un script qui génère une goutte de texte, il existe un point où un bloc de texte "récapitulatif" peut être ajouté à ce blob.Powershell: une chaîne est ajoutée plusieurs fois à une autre chaîne
Bien que le script ne génère le texte de synthèse qu'une seule fois, il est ajouté plusieurs fois au blob de texte.
Ceci est le script 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
Et ceci est le résultat lorsqu'il est exécuté:
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
J'ai utilisé un bloc de code au lieu de blockquote parce que la police à largeur fixe montre la espaces supplémentaires de premier plan.
La question: pourquoi le texte récapitulatif est-il répété trois fois au lieu d'une seule fois?
C'est une distinction subtile mais importante que Je n'avais tout simplement pas considéré jusqu'à maintenant. L'appel d'une méthode Append d'une instance StringBuilder renvoie le contenu de StringBuilder. Mettre '[void]' devant chacune de ces instructions garantissait que seul le résultat de l'appel à ToString() était renvoyé. – user1956801