String Powershell:字符串多次添加到另一个字符串
在构建文本blob的脚本中,有一个点可以将一块“摘要”文本放在所述blob的前面 尽管脚本只生成一次摘要文本,但它会多次添加到文本blob之前 这是PowerShell脚本:String Powershell:字符串多次添加到另一个字符串,string,powershell,stringbuilder,string-concatenation,String,Powershell,Stringbuilder,String Concatenation,在构建文本blob的脚本中,有一个点可以将一块“摘要”文本放在所述blob的前面 尽管脚本只生成一次摘要文本,但它会多次添加到文本blob之前 这是PowerShell脚本: # # Test_TextAppend.ps1 # $reportMessage = "Body of Report Able Was I Ere I Saw Elba"; # build "report" text $fruitList = [System.Collections.ArrayList]@(); $
#
# 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
我使用代码块而不是blockquote,因为固定宽度字体显示额外的前导空格
问题:为什么摘要文本会重复三次而不是一次?阅读:
长描述
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
,也可以从下一个语句开始):
阅读:
长描述
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
,也可以从下一个语句开始):
这是一个微妙但重要的区别,我到目前为止根本没有考虑过。调用StringBuilder实例的Append方法将返回StringBuilder的内容。将
[void]
放在这些语句的前面可以确保只返回调用ToString()的结果。这是一个微妙但重要的区别,我到目前为止根本没有考虑过。调用StringBuilder实例的Append方法将返回StringBuilder的内容。将[void]
放在这些语句的前面可以确保只返回调用ToString()的结果。