2016-08-12 116 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 
}