我继承了一个脚本,它循环遍历服务器列表中的一组服务器,然后为每个服务器输出一些内容。它使用StringBuilder将内容附加到变量中,然后吐出results...how,我是否获得了脚本来存储内容,这样我就可以在末尾显示它,而不是让它在每次迭代中打印(然后重写)。
目前,我的结果如下:
ServerName1
Text1下一轮:
ServerName2
Text 2我如何让它存储数据,然后输出以下的结尾,以便我可以通过电子邮件?
ServerName1
Text1
ServerName2
Text2我的代码:
foreach($Machine in $Machines)
{
Invoke-Command -ComputerName $Machine -ScriptBlock{param($XML1,$XML2,$XML3,$URL)
[System.Text.StringBuilder]$SB = New-Object System.Text.StringBuilder
$X = $SB.AppendLine($env:COMPUTERNAME)
if (Test-Path <path>)
{
$PolResponse = <somestuff>
$PolResponse2 = <somestuff>
Write-Host "[1st] $PolResponse" -ForegroundColor Magenta
Write-Host "[2nd] $PolResponse2" -ForegroundColor Magenta
$X = $SB.AppendLine($PolResponse)
$X = $SB.AppendLine($PolResponse2)
}
else
{
$PolResponse = "[1st] No Response"
$PolResponse2 = "[2nd] No Response"
Write-Host $PolResponse -ForegroundColor Red
Write-Host $PolResponse2 -ForegroundColor Red
$X = $SB.AppendLine($PolResponse)
$X = $SB.AppendLine($PolResponse2)
}
} -ArgumentList $XML1, $XML2, $XML3, $URL
}
# Sending result email
<<I want to send the TOTALITY of $SB here>>发布于 2017-11-02 19:00:55
您可以首先将StringBuilder变量声明移出for循环(在其之前) System.Text.StringBuilder$SB = New-Object System.Text.StringBuilder
然后为循环
发布于 2017-11-02 19:38:26
我不知道这是否是一个很好的解决方案来满足您的要求,但是您可以做的是创建一个txt文件,而foreach循环中的每个循环都将信息添加到txt文件中。这是一种存储所有信息的方法,然后在最后将所有信息放在一起。
New-Item -Path "\\Path\to\file.txt" -Itemtype File
Foreach(){
$Stuff = # Do your stuff here
Add-Content -Value $stuff -Path "\\Path\to\file.txt"
}
# Email .txt file ?
# You could use Send-MailMessage to do this possibly希望这能对你的目标有所帮助。
https://stackoverflow.com/questions/47082684
复制相似问题