2016-09-13 48 views
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 

我使用的代碼塊,而不是塊引用因爲固定寬度的字體示出了額外的領先空間。

問題:爲什麼摘要文本重複三次而不是一次?

回答

3

about_Return

詳細說明

return關鍵字退出的功能,腳本或腳本塊。它可以用於在特定點退出範圍,返回值 或指示已到達範圍的末端。

熟悉C或C#等語言的用戶可能希望使用Return關鍵字使 顯式的範圍保持邏輯。

在Windows PowerShell中,每個語句的結果返回 作爲輸出,即使沒有包含返回 關鍵字的聲明。像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); 
+0

這是一個微妙但重要的區別在於直到現在我還沒有考慮過。調用StringBuilder實例的Append方法將返回StringBuilder的內容。將'[void]'放在每個語句的前面確保只返回對ToString()的調用結果。 – user1956801

相關問題