title: powershell to report when a server uptime is above threshold
body: <p>I want to create a powershell script that check all the servers (Windows 2012 R2) on the domain, and send an e-mail report if the server up time is over the threshold that you set in the script (this case is 30 days). But I have a problem, looks like the Function do not work with my ForEach loop.</p>
  
  <p>My code so far:</p>
  
  <pre><code># Variables for sending the report
  $sender = "serviceaccount@domain.com"
  $receiver = "administrator@domain.no"
  
  # Find all the servers in the domain that need to be checked
  Get-ADComputer -filter * -properties operatingsystem | where {$_.operatingsystem -match "server"} | select name | export-csv c:\script\serverlist.csv -NotypeInformation
  
  $computer = import-csv .\serverlist.csv
  
  # Set the Threshold Limit and Deadline
  $Threshold = -30
  $Deadline = (Get-Date).AddDays($Threshold)
  
  # Function that checks the uptime
  function Get-Uptime {
     $os = Get-WmiObject win32_operatingsystem
     $uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime))
     $display = "Uptime: " + $Uptime.Days + " days" 
     Write-Output $display
  }
  
  # Then run a check on all the servers to see if the uptime is longer than the threshold
  ForEach ($computer in $computer) 
      {
      If ($uptime -ge $Deadline) 
        {
        Send-MailMessage -From $sender -To $receiver -Subject "Server $computer need to be rebooted" -Body "Server has been up for more than $Threshold days" -Priority High -dno onSuccess, onFailure -SmtpServer "mailserver.domain.com"
        }
      }
  
  # End of script
  </code></pre>