oceanblu
oceanblu

Reputation: 1

Is there a way to email specific powershell results

Test-Connection -ComputerName (Get-Content 'C:\xxxxx\xxxxx.txt') -ErrorAction Continue -Count 1 

I currently use the above command to test connections on sevreal remote PCs. It's basic and does the job, however i am looking to automate this and where i get stuck is how to filter only the failed connections from the result and output them as an email?

Thanks

really unsure how to go from here.

Upvotes: 0

Views: 47

Answers (1)

Theo
Theo

Reputation: 61068

You could do something like this:

$unreachables = Get-Content 'C:\xxxxx\xxxxx.txt' | ForEach-Object {
    if (-not (Test-Connection -ComputerName $_ -Count 1 -Quiet)) {
        # output the failed machines
        $_
    }
}
if (@($unreachables).Count) {
    # create a Hashtable with parameters used for splatting to Send-MailMessage
    # something like this
    $mailParams = @{
        From       = '[email protected]'
        To         = '[email protected]'
        Subject    = "unreachable computers"
        SmtpServer = 'mail.contoso.com'
        Body       = "The following computers are off-line ({0}):`r`n`r`n{1}" -f (Get-Date), ($unreachables -join "`r`n")
    }
    Send-MailMessage @mailParams
}
else {
    Write-Host 'All tested computers are online'
}

Upvotes: 1

Related Questions