2016-08-12 4 views
0

Ich habe im Internet versucht, einen Weg zu finden, wenn möglich, einen niedrigen Speicherplatz-Alarm von einem Google Mail-Konto an eine freigegebene Mailbox per Power Shell zu senden Frage, die ich geschafft habe, zusammenzufügen.Ein Festplattenspeicherplatzalarm per Powershell per E-Mail versenden

$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)} 

Script läuft, aber nichts passiert, wäre jede Hilfe fantastisch !!!

+0

Wenden Sie Divide and Conquer Taktik auf das Debuggen an. Brechen Sie das Skript in Teile und finden Sie heraus, welcher Teil fehlschlägt. Gibt die WMI-Abfrage gute Ergebnisse? Können Sie über Google Mail willkürliche E-Mails senden? – vonPryz

+0

Es gibt Tippfehler, die "Smtpclinet" nicht helfen werden. Warum nicht 'Send-MailMessage' verwenden? Wie auch immer, du bekommst nichts, weil du '$ tableFragment' niemals in' $ Body' zusammenführst. Wenn '$ Body' keine HTML-Tabelle mit Tabellendaten enthält, wird die Mail nie gesendet. –

+0

Ein weiteres Problem für Sie. '$ Body' wird aufgebaut, indem eine Variable' $ trimespace' eingefügt wird. Die '$ thesholdspace'-Variable wird erst gesetzt, nachdem' $ Body' den Wert bereits verwendet hat. –

Antwort

0

Meine Version wäre länger, weil ich Send-MailMessage ersetzt hätte, so dass das Tauschen zwischen mir und Send-MailMessage trivial ist.

Dies ist eine Möglichkeit, dies zu tun. Es gibt gute Verwendungen für den Fragment-Parameter in ConvertTo-Html, aber keine große Berechtigung, dies hier zu tun.

Dies ist ein Skript und wird voraussichtlich eine .ps1-Datei sein. Obligatorische Dinge, die ich nicht wirklich über einen Standard hinaus programmieren möchte, werden im Parameter Block gesetzt.

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 
}