【发布时间】:2018-01-29 21:00:56
【问题描述】:
我想创建一个 powershell 脚本来检查域上的所有服务器(Windows 2012 R2),如果服务器正常运行时间超过您在脚本中设置的阈值(这种情况是30天)。但我有一个问题,看起来函数不适用于我的 ForEach 循环。
到目前为止我的代码:
# 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
【问题讨论】:
-
现在我没有得到脚本的结果,所以任何关于如何完成这项工作的提示都非常感谢
-
你不要在循环中执行函数 Get-Uptime .. 所以变量 $uptime = $0 = $false
-
好吧,我不是程序员,我只是想学习powershell的服务器管理员。那么我应该如何在循环中使用该函数呢?
-
等我把它写成答案
-
您的函数将返回一个字符串,因此您不能在与
$Deadline的比较中使用它。此外,它会从本地计算机而不是$computer查询上次启动时间,并计算自上次重启以来的天数,而不是返回实际日期。
标签: windows powershell server active-directory windows-server-2012-r2