1. 程式人生 > >PowerShell 發送美觀的Vsphere DataStore警報

PowerShell 發送美觀的Vsphere DataStore警報

powershell html datastore

豆子今天登陸Vsphere VCenter的時候,無意中發現有DataStore的警報信息,個別DataStore的使用空間超過90%了,需要清空一下SAN Volume的Snapshot。這個是運維常見的問題,那麽順便就用PowerShell寫個腳本,定期檢查發送郵件好了。


腳本本身很容易,但是我想讓他盡量的美觀一些。

之前我寫過一個博文可以自定義sytle的樣式 http://beanxyz.blog.51cto.com/5570417/1786712, 不過現在看起來有些麻煩,還是覺得找找如果有比較好看的現成的css文件可以直接調用就好了。


上網搜了搜 table有哪些現成的css模板,隨便找了一個https://codepen.io/anon/pen/vJmLWL,看著還成

下載他的css下來

技術分享

下載的css文件,保存在C:\tmp 目錄


@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100);
body {
  background-color: #3e94ec;
  font-family: "Roboto", helvetica, arial, sans-serif;
  font-size: 16px;
  font-weight: 400;
  text-rendering: optimizeLegibility;
}
div.table-title {
   display: block;
  margin: auto;
  max-width: 600px;
  padding:5px;
  width: 100%;
}
.table-title h3 {
   color: #fafafa;
   font-size: 30px;
   font-weight: 400;
   font-style:normal;
   font-family: "Roboto", helvetica, arial, sans-serif;
   text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);
   text-transform:uppercase;
}
/*** Table Styles **/
.table-fill {
  background: white;
  border-radius:3px;
  border-collapse: collapse;
  height: 200px;
  margin: auto;
  max-width: 600px;
  padding:5px;
  width: 100%;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  animation: float 5s infinite;
}
 
th {
  color:#D5DDE5;;
  background:#1b1e24;
  border-bottom:4px solid #9ea7af;
  border-right: 1px solid #343a45;
  font-size:23px;
  font-weight: 100;
  padding:24px;
  text-align:left;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  vertical-align:middle;
}
th:first-child {
  border-top-left-radius:3px;
}
 
th:last-child {
  border-top-right-radius:3px;
  border-right:none;
}
  
tr {
  border-top: 1px solid #C1C3D1;
  border-bottom-: 1px solid #C1C3D1;
  color:#666B85;
  font-size:16px;
  font-weight:normal;
  text-shadow: 0 1px 1px rgba(256, 256, 256, 0.1);
}
 
tr:hover td {
  background:#4E5066;
  color:#FFFFFF;
  border-top: 1px solid #22262e;
  border-bottom: 1px solid #22262e;
}
 
tr:first-child {
  border-top:none;
}
tr:last-child {
  border-bottom:none;
}
 
tr:nth-child(odd) td {
  background:#EBEBEB;
}
 
tr:nth-child(odd):hover td {
  background:#4E5066;
}
tr:last-child td:first-child {
  border-bottom-left-radius:3px;
}
 
tr:last-child td:last-child {
  border-bottom-right-radius:3px;
}
 
td {
  background:#FFFFFF;
  padding:20px;
  text-align:left;
  vertical-align:middle;
  font-weight:300;
  font-size:18px;
  text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);
  border-right: 1px solid #C1C3D1;
}
td:last-child {
  border-right: 0px;
}
th.text-left {
  text-align: left;
}
th.text-center {
  text-align: center;
}
th.text-right {
  text-align: right;
}
td.text-left {
  text-align: left;
}
td.text-center {
  text-align: center;
}
td.text-right {
  text-align: right;
}


下面是正式的腳本,Set-CellColor也是別人寫好的現成的,我直接拿來用了,主要功能是根據條件來更改html文件table的格子的顏色,比如某個值大於警報線就標記為紅色等等。腳本中間加載Vsphere SnapIn,查詢datastore的狀態,最後把結果轉換為html,通過Office365發送郵件出去



#修改顏色塊的設定
Function Set-CellColor
{   
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory,Position=0)]
        [string]$Property,
        [Parameter(Mandatory,Position=1)]
        [string]$Color,
        [Parameter(Mandatory,ValueFromPipeline)]
        [Object[]]$InputObject,
        [Parameter(Mandatory)]
        [string]$Filter,
        [switch]$Row
    )
    
    Begin {
        Write-Verbose "$(Get-Date): Function Set-CellColor begins"
        If ($Filter)
        {   If ($Filter.ToUpper().IndexOf($Property.ToUpper()) -ge 0)
            {   $Filter = $Filter.ToUpper().Replace($Property.ToUpper(),"`$Value")
                Try {
                    [scriptblock]$Filter = [scriptblock]::Create($Filter)
                }
                Catch {
                    Write-Warning "$(Get-Date): ""$Filter"" caused an error, stopping script!"
                    Write-Warning $Error[0]
                    Exit
                }
            }
            Else
            {   Write-Warning "Could not locate $Property in the Filter, which is required.  Filter: $Filter"
                Exit
            }
        }
    }
    
    Process {
        ForEach ($Line in $InputObject)
        {   If ($Line.IndexOf("<tr><th") -ge 0)
            {   Write-Verbose "$(Get-Date): Processing headers..."
                $Search = $Line | Select-String -Pattern ‘<th ?[a-z\-:;"=]*>(.*?)<\/th>‘ -AllMatches
                $Index = 0
                ForEach ($Match in $Search.Matches)
                {   If ($Match.Groups[1].Value -eq $Property)
                    {   Break
                    }
                    $Index ++
                }
                If ($Index -eq $Search.Matches.Count)
                {   Write-Warning "$(Get-Date): Unable to locate property: $Property in table header"
                    Exit
                }
                Write-Verbose "$(Get-Date): $Property column found at index: $Index"
            }
            If ($Line -match "<tr( style=""background-color:.+?"")?><td")
            {   $Search = $Line | Select-String -Pattern ‘<td ?[a-z\-:;"=]*>(.*?)<\/td>‘ -AllMatches
                $Value = $Search.Matches[$Index].Groups[1].Value -as [double]
                If (-not $Value)
                {   $Value = $Search.Matches[$Index].Groups[1].Value
                }
                If (Invoke-Command $Filter)
                {   If ($Row)
                    {   Write-Verbose "$(Get-Date): Criteria met!  Changing row to $Color..."
                        If ($Line -match "<tr style=""background-color:(.+?)"">")
                        {   $Line = $Line -replace "<tr style=""background-color:$($Matches[1])","<tr style=""background-color:$Color"
                        }
                        Else
                        {   $Line = $Line.Replace("<tr>","<tr style=""background-color:$Color"">")
                        }
                    }
                    Else
                    {   Write-Verbose "$(Get-Date): Criteria met!  Changing cell to $Color..."
                        $Line = $Line.Replace($Search.Matches[$Index].Value,"<td style=""background-color:$Color"">$Value</td>")
                    }
                }
            }
            Write-Output $Line
        }
    }
    
    End {
        Write-Verbose "$(Get-Date): Function Set-CellColor completed"
    }
}
#加載Vsphere
function Load-PowerCLI
{
    #pls download and install module first
    Add-PSSnapin VMware.VimAutomation.Core
   # Add-PSSnapin VMware.VimAutomation.Vds
   # Add-PSSnapin VMware.VumAutomation
    . "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
}
#判斷是否已經加載SnapIn
$snapins=Get-PSSnapin
if($snapins.name -eq "VMware.VimAutomation.Core")
{
    Write-Host "Vsphere SnapIn is loaded" -ForegroundColor Cyan
}
else{
    Load-PowerCLI
}
#綁定VCenter
Connect-VIServer sydvcs2012

#獲取DataStore的數據

$report = @()

foreach($cluster in Get-Cluster){
    Get-VMHost -Location $cluster | Get-Datastore | %{
        $info = "" | select DataCenter, Cluster, Name, Capacity, Free, ‘UsagePercentage(%)‘
        $info.Datacenter = $_.Datacenter
        $info.Cluster = $cluster.Name
        $info.Name = $_.Name 
        $info.Capacity = [math]::Round($_.capacityMB/1024,2) 
        $info.Free="{0:N1}" -f $_.FreeSpaceGB
        $info.‘UsagePercentage(%)‘=[math]::round(100*($_.CapacityGB-$_.FreeSpaceGB)/$_.CapacityGB,2)
        $report += $info
    }
}


#通過Office365發送郵件
$from = "[email protected]
/* */" $to = "[email protected]" $smtp = "smtp.office365.com" $sub = "DataStore list" $secpasswd = ConvertTo-SecureString "Password" -AsPlainText -Force $mycreds = New-Object System.Management.Automation.PSCredential ($from, $secpasswd) #指定css模板轉換數據為html格式,根據條件指定cell的顏色 $htmlbody=$report| ConvertTo-Html -Body "<H1> DataStore </H1>" -CssUri C:\tmp\table.css | Set-CellColor -Property "UsagePercentage(%)" -Color red -Filter "UsagePercentage(%) -gt 80" #發送郵件 Send-MailMessage -To $to -From $from -Subject $sub -Body ($htmlbody|Out-String) -Credential $mycreds -SmtpServer $smtp -DeliveryNotificationOption Never -BodyAsHtml -UseSsl -port 587


我收到的郵件效果


技術分享


最後添加腳本到task scheduler裏面讓他每日自動運行就行了


技術分享

本文出自 “麻婆豆腐” 博客,請務必保留此出處http://beanxyz.blog.51cto.com/5570417/1954755

PowerShell 發送美觀的Vsphere DataStore警報