Question
Boucle conditionnelle (négation)
- lefevre
- Auteur du sujet
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 13
- Remerciements reçus 0
il y a 6 ans 10 mois #28914
par lefevre
Réponse de lefevre sur le sujet Re:Boucle conditionnelle (négation)
Salut 6ratgus
Hier soir, j'ai essayé de créer ceci
[code:1]if ($totalUpdates.count -ne 0) {
$sendMail = $smtp.Send($msg)
$sendMail = $true
}
else {$sendMail = $false}[/code:1]
Mais toujours pas, peut-être que je ne le place pas au bon endroit aussi.
Où est-ce que vous placerez cette condition ?
Pour le moment, l’exécution des scripts s'effectue localement sur chaque serveur, donc pas de soucis de ce côté-là.<br><br>Message édité par: llefevre, à: 14/05/19 10:23
Hier soir, j'ai essayé de créer ceci
[code:1]if ($totalUpdates.count -ne 0) {
$sendMail = $smtp.Send($msg)
$sendMail = $true
}
else {$sendMail = $false}[/code:1]
Mais toujours pas, peut-être que je ne le place pas au bon endroit aussi.
Où est-ce que vous placerez cette condition ?
Pour le moment, l’exécution des scripts s'effectue localement sur chaque serveur, donc pas de soucis de ce côté-là.<br><br>Message édité par: llefevre, à: 14/05/19 10:23
Connexion ou Créer un compte pour participer à la conversation.
- Philippe
- Hors Ligne
- Modérateur
-
Réduire
Plus d'informations
- Messages : 1778
- Remerciements reçus 21
il y a 6 ans 10 mois #28917
par Philippe
Réponse de Philippe sur le sujet Re:Boucle conditionnelle (négation)
tout naturelement a l'envoie du mail a la fin du script; voir le script ci-dessous ou y il a la marque <<<
a tu lu tous mon precedent message ?
en particulier sur le nombre d'ordi que tu consulte !
[code:1]#########################################################
# #
# Monitoring Windows Updates and Pending Restarts #
# #
#########################################################
#########################################################
# List of computers to be monitored
#########################################################
$Servers = Get-Content .\Machines.txt
#########################################################
# List of users who will receive the report
#########################################################
$mailto = \"Cette adresse e-mail est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser., mail2@mail.net\"
#########################################################
# SMTP properties
#########################################################
$emailFrom = \"suport@mail.net\"
$smtpServer = \"mySMTPServer\" #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>Windows Updates and Pending Restarts Report</b></h1>
<p style='font: .8em \"\"Lucida Grande\"\", Tahoma, Arial, Helvetica, sans-serif;'>This report was generated because the server(s) listed below have Windows Updates ready to be installed, Windows Updates configured to be checked manually or servers that required a reboot. Servers that do not fall under these conditions will not be listed.</p>
<br><br>
<style type=\"\"text/css\"\">body{font: .8em \"\"Lucida Grande\"\", 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;}
</style>
<body BGCOLOR=\"\"white\"\">
$tableFragment
</body>
\"@
#########################################################
# Validation and sending email
#########################################################
# Regular expression to get what's inside of <td>'s
$regexsubject = $HTMLmessage
$regex = [regex] '(?im)<td>'
# If you have data between <td>'s then you need to send the email
#if ($regex.IsMatch($regexsubject)) {
if ($totalUpdates -ne 0) { # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$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 = \"Disk Space Alert for $computer\"
$msg.IsBodyHTML = $true
$msg.Body = $HTMLmessage
$smtp.Send($msg)
}[/code:1]<br><br>Message édité par: 6ratgus, à: 14/05/19 13:45
a tu lu tous mon precedent message ?
en particulier sur le nombre d'ordi que tu consulte !
[code:1]#########################################################
# #
# Monitoring Windows Updates and Pending Restarts #
# #
#########################################################
#########################################################
# List of computers to be monitored
#########################################################
$Servers = Get-Content .\Machines.txt
#########################################################
# List of users who will receive the report
#########################################################
$mailto = \"Cette adresse e-mail est protégée contre les robots spammeurs. Vous devez activer le JavaScript pour la visualiser., mail2@mail.net\"
#########################################################
# SMTP properties
#########################################################
$emailFrom = \"suport@mail.net\"
$smtpServer = \"mySMTPServer\" #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>Windows Updates and Pending Restarts Report</b></h1>
<p style='font: .8em \"\"Lucida Grande\"\", Tahoma, Arial, Helvetica, sans-serif;'>This report was generated because the server(s) listed below have Windows Updates ready to be installed, Windows Updates configured to be checked manually or servers that required a reboot. Servers that do not fall under these conditions will not be listed.</p>
<br><br>
<style type=\"\"text/css\"\">body{font: .8em \"\"Lucida Grande\"\", 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;}
</style>
<body BGCOLOR=\"\"white\"\">
$tableFragment
</body>
\"@
#########################################################
# Validation and sending email
#########################################################
# Regular expression to get what's inside of <td>'s
$regexsubject = $HTMLmessage
$regex = [regex] '(?im)<td>'
# If you have data between <td>'s then you need to send the email
#if ($regex.IsMatch($regexsubject)) {
if ($totalUpdates -ne 0) { # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$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 = \"Disk Space Alert for $computer\"
$msg.IsBodyHTML = $true
$msg.Body = $HTMLmessage
$smtp.Send($msg)
}[/code:1]<br><br>Message édité par: 6ratgus, à: 14/05/19 13:45
Connexion ou Créer un compte pour participer à la conversation.
- lefevre
- Auteur du sujet
- Hors Ligne
- Nouveau membre
-
Réduire
Plus d'informations
- Messages : 13
- Remerciements reçus 0
il y a 6 ans 10 mois #28920
par lefevre
Réponse de lefevre sur le sujet Re:Boucle conditionnelle (négation)
Merci pour le retour, de cette manière ça fonctionne.
[code:1]# If you have data between <td>'s then you need to send the email
if ($regex.IsMatch($regexsubject)){
if ($totalUpdates -ne 0) {
$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)
}
}[/code:1]
Oui, j'ai lu votre dernier message, mais comme je n'ai jamais réussi à exécuter ce script à distance à cause d'un problème de crédentials (voir un autre post là-dessus sur ce forum) j'ai abandonné l'idée.
powershell-scripting.com/index.php?optio...25&catid=5#27925
Donc, comme je vous l'ai précisé dans le message précédent, je surveille chaque poste un par un.
Idéalement, j'aimerais pouvoir exécuter ce script directement sur le serveur et récupérer la liste de tous les serveurs en un seul mail, mais je n'y suis jamais parvenu.<br><br>Message édité par: llefevre, à: 15/05/19 09:13
[code:1]# If you have data between <td>'s then you need to send the email
if ($regex.IsMatch($regexsubject)){
if ($totalUpdates -ne 0) {
$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)
}
}[/code:1]
Oui, j'ai lu votre dernier message, mais comme je n'ai jamais réussi à exécuter ce script à distance à cause d'un problème de crédentials (voir un autre post là-dessus sur ce forum) j'ai abandonné l'idée.
powershell-scripting.com/index.php?optio...25&catid=5#27925
Donc, comme je vous l'ai précisé dans le message précédent, je surveille chaque poste un par un.
Idéalement, j'aimerais pouvoir exécuter ce script directement sur le serveur et récupérer la liste de tous les serveurs en un seul mail, mais je n'y suis jamais parvenu.<br><br>Message édité par: llefevre, à: 15/05/19 09:13
Connexion ou Créer un compte pour participer à la conversation.
- Philippe
- Hors Ligne
- Modérateur
-
Réduire
Plus d'informations
- Messages : 1778
- Remerciements reçus 21
il y a 6 ans 10 mois #28942
par Philippe
un nom par ligne avec le nom de domaine compris
ex :
serveur1.domaine.com
ordinateur.domaine.com
etc
Réponse de Philippe sur le sujet Re:Boucle conditionnelle (négation)
dans le fichier serveurs.txt il te faut mettre les noms des serveursIdéalement, j'aimerais pouvoir exécuter ce script directement sur le serveur et récupérer la liste de tous les serveurs en un seul mail, mais je n'y suis jamais parvenu.
un nom par ligne avec le nom de domaine compris
ex :
serveur1.domaine.com
ordinateur.domaine.com
etc
Connexion ou Créer un compte pour participer à la conversation.
Temps de génération de la page : 0.042 secondes
- Vous êtes ici :
-
Accueil
-
forum
-
PowerShell
-
Entraide pour les débutants
- Boucle conditionnelle (négation)