Script error - Send an email

Welcome Forums General PowerShell Q&A Script error - Send an email

This topic contains 5 replies, has 3 voices, and was last updated by

 
Participant
3 months, 2 weeks ago.

  • Author
    Posts
  • #132042

    Participant
    Points: 56
    Rank: Member

    Hi,

    I need to found a monitoring solution in order to run a script that reports new updates available on the WSUS Server.

    Scripts are executed locally.

    It works on 49 serveurs, but there's one that gives me a hard time.

    I get this error message.

    Exception calling "Send" with "1" argument(s): "Failure to send the mail."
    At C:\Temp\script_notif.ps1:172 char:7
    + $smtp.Send($msg)
    + ~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

    Do you have any idea ?

    Thank you for your help.

    #########################################################
    #                                                       #
    # Monitoring Windows Updates and Pending Restarts       #
    #                                                       #
    #########################################################
    
    #########################################################
    # List of computers to be monitored
    #########################################################
    $Servers "10.254.x.x"
    
    #########################################################
    # List of users who will receive the report
    #########################################################
    $mailto "x"
    
    #########################################################
    # SMTP properties
    #########################################################
    $emailFrom "x"
    $smtpServer "x" #SMTP Server. 
    #$smtpUsername = "myUsername"
    #$smtpPassword = "myPassword"
    
    $results = foreach ($Computer in $Servers) 
    { 
        try 
          { 
              $service Get-WmiObject Win32_Service -Filter 'Name="wuauserv"' -ComputerName $Computer -Ea 0
            $WUStartMode $service.StartMode
            $WUState $service.State
            $WUStatus $service.Status
          
            try{
                if (Test-Connection -ComputerName $Computer -Count 1 -Quiet)
                { 
                    #check if the server is the same where this script is running
                    if($Computer -eq "$env:computername.$env:userdnsdomain")
                    {
                        $UpdateSession = New-Object -ComObject Microsoft.Update.Session
                    }
                    else { $UpdateSession = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session",$Computer)) }
                    $UpdateSearcher $UpdateSession.CreateUpdateSearcher()
                    $SearchResult $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
                    $Critical $SearchResult.updates where $_.MsrcSeverity -eq "Critical" }
                    $important $SearchResult.updates where $_.MsrcSeverity -eq "Important" }
                    $other $SearchResult.updates where $_.MsrcSeverity -eq $null }
                    # Get windows updates counters
                    $totalUpdates = $($SearchResult.updates.count)
                    $totalCriticalUp = $($Critical.count)
                    $totalImportantUp = $($Important.count)
                    
                    if($totalUpdates -gt 0)
                    {
                        $updatesToInstall $true
                    }
                    else { $updatesToInstall $false }
                }
                else
                {
                    # if cannot connected to the server the updates are listed as not defined
                    $totalUpdates "nd"
                    $totalCriticalUp "nd"
                    $totalImportantUp "nd"
                }
            }
            catch 
            { 
                # if an error occurs the updates are listed as not defined
                Write-Warning "$Computer`: $_" 
                 $totalUpdates "nd"
                $totalCriticalUp "nd"
                $totalImportantUp "nd"
                $updatesToInstall $false
            }
      
            # Querying WMI for build version 
            $WMI_OS Get-WmiObject -Class Win32_OperatingSystem -Property BuildNumberCSName -ComputerName $Computer -Authentication PacketPrivacy -Impersonation Impersonate
    
            # Making registry connection to the local/remote computer 
            $RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"LocalMachine",$Computer) 
             
            # If Vista/2008 & Above query the CBS Reg Key 
            If ($WMI_OS.BuildNumber -ge 6001) 
            { 
                $RegSubKeysCBS $RegCon.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\").GetSubKeyNames() 
                $CBSRebootPend $RegSubKeysCBS -contains "RebootPending" 
            }
            else{
                $CBSRebootPend $false
            }
               
            # Query WUAU from the registry 
            $RegWUAU $RegCon.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\") 
            $RegSubKeysWUAU $RegWUAU.GetSubKeyNames() 
            $WUAURebootReq $RegSubKeysWUAU -contains "RebootRequired" 
            
            If($CBSRebootPend –OR $WUAURebootReq)
            {
                $machineNeedsRestart $true
            }
            else
            {
                $machineNeedsRestart $false
            }
             
            # Closing registry connection 
            $RegCon.Close() 
            
            if($machineNeedsRestart -or $updatesToInstall -or ($WUStartMode -eq "Manual") -or ($totalUpdates -eq "nd"))
            {
                New-Object PSObject -Property @{
                       Computer $WMI_OS.CSName 
                    WindowsUpdateStatus $WUStartMode "/" $WUState "/" $WUStatus 
                    UpdatesToInstall $updatesToInstall 
                    TotalOfUpdates $totalUpdates  
                    TotalOfCriticalUpdates $totalCriticalUp 
                    TotalOfImportantUpdates $totalImportantUp
                    RebootPending $machineNeedsRestart
                }
            }
          }
        Catch 
         { 
            Write-Warning "$Computer`: $_" 
          }
    }
    
    #########################################################
    # Formating result
    #########################################################
    $tableFragment $results ConvertTo-HTML -fragment
    
    # HTML Format for Output 
    $HTMLmessage = @"
    
    

    Rapport des majs en attentes et/ou d'un redemarrage en attente

    Ce rapport a été  généré car il y a des updates en attentes d'installation et/ou d'un reboot en attente sur ce  serveur. Merci de suivre la procédure : http://doc4tme.all4it.local/doku.php/clients/a4i_it/system/ majs_4cliwinrdpgwa .



    $tableFragment "
    @ ######################################################### # Validation and sending email ######################################################### # Regular expression to get what's inside of 's $regexsubject $HTMLmessage $regex = [regex'(?im)' # If you have data between 's then you need to send the email if ($regex.IsMatch($regexsubject)) {      $smtp = New-Object Net.Mail.SmtpClient -ArgumentList $smtpServer        #$smtp.credentials = New-Object System.Net.NetworkCredential($smtpUsername, $smtpPassword);        $msg = New-Object Net.Mail.MailMessage      $msg.From $emailFrom      $msg.To.Add($mailto)      $msg.Subject "Update et/ou reboot en attente sur $computer"      $msg.IsBodyHTML $true      $msg.Body $HTMLmessage           $smtp.Send($msg)    }
  • #132045

    Participant
    Points: 167
    Helping Hand
    Rank: Participant

    If it works on 49 servers, but not one, surely this points to the issue being local to that server not to the script?

    Looking at the error, it states it failed to send the mail, so i'd start with looking at the SMTP relay configuration first (checking that the single failed server can reach\access it), then stepping out to firewall rules etc.

    Start with simple SMTP testing from that single server to elimate networking issues:

    https://docs.microsoft.com/en-us/exchange/mail-flow/test-smtp-with-telnet?view=exchserver-2019

  • #132332

    Participant
    Points: 56
    Rank: Member

    Thank you for your answer.

    Yes, it is a local problem, because it is the same script for all servers.

    The port to the SMTP relay is open.

    What should I look for in the firewall?

  • #132347

    Participant
    Points: 167
    Helping Hand
    Rank: Participant

    Without knowing the environment, difficult to say. These would be my first troubleshooting steps...

    • Is the troublesome host on a different network/vlan to the others?
    • If so, are there any rules preventing source traffic from the troublesome host on the main router/core switch/gateway etc
    • Can you access the SMTP server using the guidance notes I sent above from the troublesome host?

     

  • #132744

    Participant
    Points: 56
    Rank: Member

    Thanks for the feedback.

    We checked the PowerShell version and the framework.
    Everything's fine on that side.

    The same goes for the firewall.

    Until my colleague looks at the script in question and realizes that the @ip is not the one of the SMTP gateway.

    Beginner's mistake.
    The problem is solved.

    Have a great weekend to you.

  • #132813

    Participant
    Points: 342
    Helping Hand
    Rank: Contributor

    Did you know the mailing functionality is built in WSUS?

    If you want to configure it on multiple computers, you can use the PoshWSUS module from the PowerShell Gallery.
    It contains a cmdlet named Set-PSWSUSEmailConfig which allows you to configure your WSUS notifications.

The topic ‘Script error - Send an email’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort