2016-08-12 118 views
0

我一直在瀏覽網頁,試圖找到一種方法,如果可能的話,從Gmail帳戶通過電子郵件發送到共享郵箱的磁盤空間不足警報,但我正在努力與一個查詢我已經拼湊起來了。通過電子郵件發送硬盤磁盤空間警報使用Powershell

$EmailFrom = "[email protected]" 
$EmailTo = "[email protected]" 
$SMTPServer = "smtp.gmail.com" 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("Username", "Password"); 
$Computers = "Local Computer" 
$Subject = "Disk Space Storage Report" 
$Body = "This report was generated because the drive(s) listed below have less than $thresholdspace % free space. Drives above this threshold will not be listed." 

[decimal]$thresholdspace = 50 

$tableFragment = Get-WMIObject -ComputerName $computers Win32_LogicalDisk ` 
| select __SERVER, DriveType, VolumeName, Name, @{n='Size (Gb)' ;e={"{0:n2}" -f ($_.size/1gb)}},@{n='FreeSpace (Gb)';e={"{0:n2}" -f ($_.freespace/1gb)}}, @{n='PercentFree';e={"{0:n2}" -f ($_.freespace/$_.size*100)}} ` 
| Where-Object {$_.DriveType -eq 3} ` 
| ConvertTo-HTML -fragment 

$regexsubject = $Body 
$regex = [regex] '(?im)<td>' 

if ($regex.IsMatch($regexsubject)) {$smtpclinet.send($fromemail, $EmailTo, $Subject, $Body)} 

腳本運行但沒有任何反應,任何幫助將是太棒了!

+0

將分而治之的策略運用到調試中。分解腳本並找出哪部分失敗。 WMI查詢是否報告了良好的結果?你可以通過Gmail發送任意郵件嗎? – vonPryz

+0

有錯別字不會幫助'smtpclinet'。爲什麼不使用Send-MailMessage?無論如何,你一無所獲,因爲你永遠不會將'$ tableFragment'合併到'$ Body'中。如果'$ Body'不包含具有表格數據的HTML表格,則郵件永遠不會被髮送。 –

+0

您的另一個問題。 '$ Body'構建了一個'$ thresholdspace'變量。 '$ thesholdspace'變量在'$ Body'已經使用該值之後才被設置。 –

回答

0

我的版本會更長,因爲我已經取代了Send-MailMessage,這樣我和Send-MailMessage之間的交換就變得微不足道了。

這是一種可能的方式。對ConvertTo-Html的Fragment參數有很好的用處,但這裏沒有太多的理由要這樣做。

這是一個腳本,預計是一個.ps1文件。強制性的東西,我真的不想硬編碼超過默認設置在參數塊。

param(
    [String[]]$ComputerName = $env:COMPUTERNAME, 

    [Decimal]$Theshold = 0.5, 

    [PSCredential]$Credential = (Get-Credential) 
) 

# 
# Supporting functions 
# 

# This function acts in much the same way as Send-MailMessage. 
function Send-SmtpMessage { 
    param(
     [Parameter(Mandatory = $true, Position = 1)] 
     [String[]]$To, 

     [Parameter(Mandatory = $true, Position = 2)] 
     [String]$Subject, 

     [String]$Body, 

     [Switch]$BodyAsHtml, 

     [String]$SmtpServer = $PSEmailServer, 

     [Int32]$Port, 

     [Switch]$UseSSL, 

     [PSCredential]$Credential, 

     [Parameter(Mandatory = $true)] 
     [String]$From 
    ) 

    if ([String]::IsNullOrEmtpy($_)) { 
     # I'd use $pscmdlet.ThrowTerminatingError for this normally 
     throw 'A value must be provided for SmtpServer' 
    } 

    # Create a mail message 
    $mailMessage = New-Object System.Net.Mail.MailMessage 
    # Email address formatting si validated by this, allowing failure to kill the command 
    try { 
     foreach ($recipient in $To) { 
      $mailMessage.To.Add($To) 
     } 
     $mailMessage.From = $From 
    } catch { 
     $pscmdlet.ThrowTerminatingError($_) 
    } 
    $mailMessage.Subject = $Subject 

    $mailMessage.Body = $Body 
    if ($BodyAsHtml) { 
     $mailMessage.IsBodyHtml = $true 
    } 

    try { 
     $smtpClient = New-Object System.Net.Mail.SmtpClient($SmtpServer, $Port) 
     if ($UseSSL) { 
      $smtpClient.EnableSsl = $true 
     } 
     if ($psboundparameters.ContainsKey('Credential')) { 
      $smtpClient.Credentials = $Credential.GetNetworkCredential() 
     } 

     $smtpClient.Send($mailMessage) 
    } catch { 
     # Return errors as non-terminating 
     Write-Error -ErrorRecord $_ 
    } 
} 

# 
# Main 
# 

# This is inserted before the table generated by the script 
$PreContent = 'This report was generated because the drive(s) listed below have less than {0} free space. Drives above this threshold will not be listed.' -f ('{0:P2}' -f $Threshold) 

# This is a result counter, it'll be incremented for each result which passes the threshold 
$i = 0 
# Generate the message body. There's not as much error control around WMI as I'd normally like. 
$Body = Get-WmiObject Win32_LogicalDisk -Filter 'DriveType=3' -ComputerName $ComputerName | ForEach-Object { 
    # PSCustomObject requires PS 3 or greater. 
    # Using Math.Round below means we can still perform numeric comparisons 
    # Percent free remains as a decimal until the end. Programs like Excel expect percentages as a decimal (0 to 1). 
    [PSCustomObject]@{ 
     ComputerName  = $_.__SERVER 
     DriveType  = $_.DriveType 
     VolumeName  = $_.VolumeName 
     Name    = $_.Name 
     'Size (GB)'  = [Math]::Round(($_.Size/1GB), 2) 
     'FreeSpace (GB)' = [Math]::Round(($_.FreeSpace/1GB), 2) 
     PercentFree  = [Math]::Round(($_.FreeSpace/$_.Size), 2) 
    } 
} | Where-Object { 
    if ($_.PercentFree -lt $Threshold) { 
     $true 
     $i++ 
    } 
} | ForEach-Object { 
    # Make Percentage friendly. P2 adds % for us. 
    $_.PercentFree = '{0:P2}' -f $_.PercentFree 

    $_ 
} | ConvertTo-Html -PreContent $PreContent | Out-String 

# If there's one or more warning to send. 
if ($i -gt 0) { 
    $params = @{ 
     To   = "[email protected]" 
     From  = "[email protected]" 
     Subject = "Disk Space Storage Report" 
     Body  = $Body 
     SmtpServer = "smtp.gmail.com" 
     Port  = 587 
     UseSsl  = $true 
     Credential = $Credential 
    } 
    Send-SmtpMessage @params 
}