Question [Résolu] Erreur script - envoyer un mail

Plus d'informations
il y a 7 ans 2 mois #27983 par lefevre
Bonjour,

Je dois trouver une solution de monitoring afin d'exécuter un script qui remonte les nouvelles mises à jour disponible sur le serveur WSUS.

Les scripts s'exécutent en local.

Cela fonctionne sur 49 serveurs, mais il y en a un qui me donne du fil à retordre.

[code:1]#########################################################
# #
# 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 BuildNumber, CSName -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 = @\"
<font color=\"\"black\"\" face=\"\"Arial\"\" size=\"\"3\"\">
<h1 style='font-family:arial;'><b>Rapport des majs en attentes et/ou d'un redemarrage en attente</b></h1>
&lt;p style='font: .8em \&quot;\&quot;Lucida Grande\&quot;\&quot;, Tahoma, Arial, Helvetica, sans-serif;'&gt;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 : doc4tme.all4it.local/doku.php/clients/a4...m/majs_4cliwinrdpgwa .</p>
&lt;br&gt;&lt;br&gt;
&lt;style type=\&quot;\&quot;text/css\&quot;\&quot;&gt;body{font: .8em \&quot;\&quot;Lucida Grande\&quot;\&quot;, Tahoma, Arial, Helvetica, sans-serif;}
ol{margin:0;}
table{width:80%;}
thead{}
thead th{font-size:120%;text-align:left;}
th{border-bottom:2px solid rgb(79,129,189);border-top:2px solid rgb(79,129,189);padding-bottom:10px;padding-top:10px;}
tr{padding:10px 10px 10px 10px;border:none;}
#middle{background-color:#900;}
&lt;/style&gt;
&lt;body BGCOLOR=\&quot;\&quot;white\&quot;\&quot;&gt;
$tableFragment
&lt;/body&gt;
\&quot;@


#########################################################
# Validation and sending email
#########################################################
# Regular expression to get what's inside of &lt;td&gt;'s
$regexsubject = $HTMLmessage
$regex = [regex] '(?im)&lt;td&gt;'

# If you have data between &lt;td&gt;'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 = \&quot;Update et/ou reboot en attente sur $computer\&quot;
$msg.IsBodyHTML = $true
$msg.Body = $HTMLmessage
$smtp.Send($msg)
}[/code:1]

J'obtiens ce message d'erreur :

Exception calling \&quot;Send\&quot; with \&quot;1\&quot; argument(s): \&quot;Échec d'envoi du courrier.\&quot;
At C:\Temp\script_notif.ps1:172 char:7
+ $smtp.Send($msg)
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException


Avez-vous une idée ?

Merci pour votre aide.

Message édité par: llefevre, à: 31/12/18 10:04<br><br>Message édité par: Arnaud, à: 4/01/19 16:45

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 7 ans 2 mois #27990 par Philippe
Réponse de Philippe sur le sujet Re:Erreur script - envoyer un mail
salut llefevre

si t'a un soucis sur un seul sur 50 serveurs, c'est que le problème viens du serveur ou d'un blocage firewall derrière lequel il se trouve.

vu le message ça laisse à penser a un problème de version de PowerShell ou du Framework.net
peut tu comparer par rapport a un autre serveur avec le même OS et mettre a jour PowerShell

mais cette partie du message \&quot;Échec d'envoi du courrier.\&quot; indique plus : blocage port ou erreur d'authentification

ou encore une erreur de frappe dans le script sur ce serveur, si le script est local ça peut être ça

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 7 ans 2 mois #27997 par lefevre
Réponse de lefevre sur le sujet Re:Erreur script - envoyer un mail
Salut 6ratgus

Merci pour le retour.

On a vérifié la version de PowerShell ainsi que le framework.
Tout est bon de ce côté-là.

Pareil au niveau du firewall.

Jusqu'à ce que mon collègue regarde le script en question et se rend compte que l'@ip n'est pas celle de la passerelle SMTP.

Erreur du débutant.
Le problème est résolu.

Très bon weekend à vous.

Connexion ou Créer un compte pour participer à la conversation.

Temps de génération de la page : 0.043 secondes
Propulsé par Kunena