DCDIAG E-mail Reports

I currently have the below code that runs DCDIAG on all of our domain controllers and e-mails me the results.

$Sender = 'DCDiagReports@Contoso.com'
$Recipients = 'user1@contoso.com'
$MessageSubject = 'DCDiag Reports'
$Relay = 'relay.contoso.local'
$DcDiag = Get-ADDomainController -Filter * | ForEach-Object {DCDiag /s:$($_.HostName)}

$email = @{
From = $Sender
To =$Recipients
Subject = $MessageSubject
SMTPServer = $Relay
Body = ($dcdiag | Out-String)
}

send-mailmessage @email

The issue I have is that the results for four domain controllers is put into one e-mail and is difficult to read. I would like to get a separate e-mail for each DC and have tried a few different things but can’t seem to get it to work…

You just need to re-arrange you code to put the send-mailmessage inside the foreach loop

$Sender = ‘DCDiagReports@Contoso.com’
$Recipients = ‘user1@contoso.com’
$MessageSubject = ‘DCDiag Reports’
$Relay = ‘relay.contoso.local’
Get-ADDomainController -Filter * |
ForEach-Object {

$dcdiag = DCDiag /s:$($_.HostName)

$email = @{
From = $Sender
To =$Recipients
Subject = $MessageSubject
SMTPServer = $Relay
Body = ($dcdiag | Out-String)
}

send-mailmessage @email
}

should work

Brilliant, exactly what I needed. Thanks Richard!