在 foreach 结束时输出 ALL 结果,而不是在每次运行期间



我继承了一个脚本,该脚本循环遍历服务器列表中的一组服务器,然后为每个服务器输出一些内容。它使用 StringBuilder 将内容附加到变量中,然后吐出结果......如何让脚本存储内容,以便我可以在最后显示整个 foreach 的结果,而不是在每次迭代时打印(然后覆盖)它?

目前我的结果如下所示:

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>>

你可以从将 StringBuilder 变量声明移到 for 循环之外(在它之前)开始[System.Text.StringBuilder]$SB = New-Object System.Text.StringBuilder

然后 FOR 循环

我不知道

这是否是您要求的好解决方案,但是您可以做的是创建一个 txt 文件,foreach 循环中的每个循环都将信息添加到 txt 文件中。这是存储所有信息,然后在最后将所有信息放在一起的一种方法。

New-Item -Path "\Pathtofile.txt" -Itemtype File
Foreach(){
    $Stuff = # Do your stuff here
    Add-Content -Value $stuff -Path "\Pathtofile.txt"
}
# Email .txt file ?
# You could use Send-MailMessage to do this possibly

希望这对您的目标有所帮助。

相关内容

最新更新