none
Разный цвет строк в зависимости от значения RRS feed

  • Вопрос

  • Добрый день. Скрипт Отправляет отчет на email в виде HTML. Помогите добавить в скрипт раскраску строк, в зависимости от значения.  Если < 10 то зеленым, от 11 до 20 желтым, > 20 красным. 

    $Servers = Get-Content D:\Servers_new.txt
    # Получатели
    $mailto = "mail@mail.ru"
    # Настройки почты
    $emailFrom = "mail@mail.ru"
    $smtpServer = "smtp.loc" #SMTP Server.
    $smtpUsername = "loc\mail"
    $smtpPassword = "pass"
    $now = Get-Date -Format d
    
    $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")
    				$other = $SearchResult.updates | where { $_.MsrcSeverity -eq $null }
    				# Get windows updates counters
    				$totalUpdates = $($SearchResult.updates.count)
    	
    			}
    			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" 
    		  
            # Closing registry connection 
            $RegCon.Close() 
    		
    		if($totalUpdates -gt 0)
    		{
    		Write-Host "$Computer`: $_ $totalUpdates"
    		}
    		if($totalUpdates -gt 0) 
    		{
    			New-Object PSObject -Property @{
    	         	TotalCount = $totalUpdates
                    Computer = $WMI_OS.CSName 
            	}
    		}
      	}
    	Catch 
     	{ 
        	Write-Warning "$Computer`: $_" 
      	}
    }
    
    
    # Formating result
    $tableFragmentSql = $results|?{$_.computer -match "sql"} |convertto-html -fragment
    $tableFragmentNot = $results|?{$_.computer -notmatch "sql"} |convertto-html -fragment
    # HTML Format for Output 
    $HTMLmessage = @"
    <font color=""black"" face=""Arial"" size=""3"">
    <h1 style='font-family:arial;'><b>Windows Updates $now</b></h1>
    <p style='font: .8em ""Lucida Grande"", Tahoma, Arial, Helvetica, sans-serif;'>Отчет ожидаемых обновлений на серверах</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"">
    <style>
    TABLE {border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse;}
    TH {background-color:#a7a7a7;}
    TD {border-width: 1px; padding: 3px; border-style: solid; border-color: black;}
    </style>
    <h2>Базы данных</h2>
    $tableFragmentSql
    <h2>Остальные</h2>
    $tableFragmentNot
    </body>
    "@
    
    # Validation and sending email
    
    $regexsubject = $HTMLmessage
    $regex = [regex] '(?im)<td>'
    
    $HTMLmessage
    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 = "Windows Update"
         $msg.IsBodyHTML = $true
         $msg.Body = $HTMLmessage    
          $smtp.Send($msg)   
    }

    10 ноября 2017 г. 6:51

Ответы

  • $s = @{
    	"sql"     = ""
    	"mail"    = ""
    	"tn"      = ""
    	"other"   = ""
    }
    
    foreach($i in $results) {
    	
    	switch($i.TotalCount)
    	{
    		{$_ -lt 10} {$color = "#00ff00";break}
    		{$_ -ge 11 -and $_ -lt 20} {$color = "#ffff00";break}
    		{$_ -gt 20} {$color = "#ff0000";break}
    		default {$color = "#000000";break}
    	}
    	
    	$t = "<tr><td>{0}</td><td bgcolor=`"{2}`">{1}</td><tr>`r`n" -f $i.Computer,$i.TotalCount,$color
    	
    	switch -Regex ($i.Computer)
    	{
    		"sql"  {$s["sql"] += $t;break}
    		"mail" {$s["mail"] += $t;break}
    		"tn"   {$s["tn"] += $t;break}
    		default {$s["other"] += $t;break}
    	}
    }
    
    $tmpl = "<table><colgroup><col/><col/></colgroup><tr><th>Computer</th><th>TotalCount</th></tr>`r`n{0}</table>"
    
    $s.GetEnumerator() | Foreach {
    	if($_.Value) {
    		$html = $tmpl -f $_.Value
    		New-Variable -Name "tableFragment$($_.Name)" -Value $html -Force
    	}
    }

    • Помечено в качестве ответа alexaf 13 ноября 2017 г. 6:10
    10 ноября 2017 г. 13:01
    Отвечающий

Все ответы

  • Заменить секцию # Formating result на:

    $sql = ""
    $notsql = ""
    foreach($i in $results) {
    	switch($i.TotalCount)
    	{
    		{$_ -lt 10} {$color = "#00ff00";break}
    		{$_ -ge 11 -and $_ -lt 20} {$color = "#ffff00";break}
    		{$_ -gt 20} {$color = "#ff0000";break}
    		default {$color = "#000000";break}
    	}
    	
    	$t = "<tr><td>{0}</td><td bgcolor=`"{2}`">{1}</td><tr>`r`n" -f $i.Computer,$i.TotalCount,$color
    	if($i.Computer -match "sql") {
    		$sql += $t
    	} else {
    		$notsql += $t
    	}
    }
    
    $tmpl = "<table><colgroup><col/><col/></colgroup><tr><th>Computer</th><th>TotalCount</th></tr>`r`n{0}</table>"
    
    if ($sql) {
    	$tableFragmentSql = $tmpl -f $sql
    } else {
    	$tableFragmentNot = $tmpl -f $notsql
    }


    • Изменено KazunEditor 10 ноября 2017 г. 8:19
    • Предложено в качестве ответа Vector BCOModerator 10 ноября 2017 г. 8:26
    10 ноября 2017 г. 8:19
    Отвечающий
  • А если будет не 2 условия, а больше. То как быть

    # Formating result
    $tableFragmentSql = $results|?{$_.computer -match "sql"} |convertto-html -fragment
    $tableFragmentMail = $results|?{$_.computer -match "mail"}|convertto-html -fragment
    $tableFragmentTN = $results|?{$_.computer -match "tn"}|convertto-html -fragment

    10 ноября 2017 г. 12:30
  • $s = @{
    	"sql"     = ""
    	"mail"    = ""
    	"tn"      = ""
    	"other"   = ""
    }
    
    foreach($i in $results) {
    	
    	switch($i.TotalCount)
    	{
    		{$_ -lt 10} {$color = "#00ff00";break}
    		{$_ -ge 11 -and $_ -lt 20} {$color = "#ffff00";break}
    		{$_ -gt 20} {$color = "#ff0000";break}
    		default {$color = "#000000";break}
    	}
    	
    	$t = "<tr><td>{0}</td><td bgcolor=`"{2}`">{1}</td><tr>`r`n" -f $i.Computer,$i.TotalCount,$color
    	
    	switch -Regex ($i.Computer)
    	{
    		"sql"  {$s["sql"] += $t;break}
    		"mail" {$s["mail"] += $t;break}
    		"tn"   {$s["tn"] += $t;break}
    		default {$s["other"] += $t;break}
    	}
    }
    
    $tmpl = "<table><colgroup><col/><col/></colgroup><tr><th>Computer</th><th>TotalCount</th></tr>`r`n{0}</table>"
    
    $s.GetEnumerator() | Foreach {
    	if($_.Value) {
    		$html = $tmpl -f $_.Value
    		New-Variable -Name "tableFragment$($_.Name)" -Value $html -Force
    	}
    }

    • Помечено в качестве ответа alexaf 13 ноября 2017 г. 6:10
    10 ноября 2017 г. 13:01
    Отвечающий