Powershell EMail:用于发送电子邮件的脚本无法在我的窗口上运行

时间:2015-11-16 10:51:45

标签: powershell scheduled-tasks

我不是来自Powershell背景。

我即将安排邮件需要发送的任务;如果磁盘大小小于预期限制。

以下是我正在使用的脚本:

$servers = Get-Content "C:\serverlist.txt";

foreach($server in $servers)
{
 # Get fixed drive info
  $disks = Get-WmiObject -ComputerName $server -Class Win32_LogicalDisk -Filter "DriveType = 3";
  foreach($disk in $disks)
  {
      $deviceID = $disk.DeviceID;
      [float]$size = $disk.Size;
      [float]$freespace = $disk.FreeSpace;

     #Here you have to mention the drive id for example i mentioned 'C' drive below
     if($deviceID -eq "C:")
     {
       $percentFree = [Math]::Round(($freespace / $size) * 100, 2);
       $sizeGB = [Math]::Round($size / 1073741824, 2);
       $freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);

       if($freeSpaceGB -lt 100)
       {
          $EmailFrom = "monitoring@mydomainname.no"
          $EmailTo = "fatherazrael@evry.com"
          $Subject = "Disk Space"
          $Body = "$disk drive space is less free space in $server server: $freeSpaceGB"
          $SMTPServer = "scan.opinkerfi.is"
          $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
          #$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("<From mail ID>", "Password"); //Not Required
          $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)   
       }
    }
 }
}

我不知道如何应用日志记录。任何人都可以找出问题所在吗?事件查看器或任何地方都没有日志。

我可以使用事件查看器,任务计划程序和性能工具配置所有这些,但我被告知要使用Powershell。

1 个答案:

答案 0 :(得分:0)

你的脚本对我有用。可能是你的磁盘空间超过100GB?

if($ freeSpaceGB -lt 100)

您可以使用一些错误处理。尝试将电子邮件发送部分更改为:

if($freeSpaceGB -lt 1000)
       {
        try {
              $EmailFrom = "monitoring@mydomainname.no"
              $EmailTo = "fatherazrael@evry.com"
              $Subject = "Disk Space"
              $Body = "$disk drive space is less free space in $server server: $freeSpaceGB"
              $SMTPServer = "scan.opinkerfi.is"
              $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
              #$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("<From mail ID>", "Password"); //Not Required
              $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
            }
        catch
            {
                $Error[0].Exception.Message | Out-File ($server + '_error.txt')
            } 

在使用txt文件将电子邮件发送到当前目录期间,您将收到相关错误。