在Powershell中检查远程服务器的UPTIME

时间:2015-01-20 12:07:00

标签: powershell

我正在尝试使用我脚本中的以下代码片段来检索远程服务器的UPTIME。

$lastboottime = (Get-WMIObject -Class Win32_OperatingSystem -ComputerName     $server -Credential $altcreds -ErrorAction SilentlyContinue).LastBootUpTime
$sysuptime = (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime)
$uptime = "   UPTIME           :    $($sysuptime.days) Days, $($sysuptime.hours) Hours, $($sysuptime.minutes) Minutes, $($sysuptime.seconds) Seconds"

执行脚本时出现以下错误:

Exception calling "ToDateTime" with "1" argument(s): "Specified argument was out of the range of valid values.
Parameter name: dmtfDate"

我无法确定错误消息是什么参数需要什么?

谢谢!

2 个答案:

答案 0 :(得分:5)

将WMI-Objects上的时间值转换为datetime-objects可以通过调用对象本身的ConvertToDateTime方法来完成。

简单示例:

$wmi = Get-WMIObject -Class Win32_OperatingSystem
$lastboottime = $wmi.ConvertToDateTime($wmi.LastBootUpTime)
$sysuptime = (Get-Date) - $lastboottime
$uptime = "   UPTIME           :    $($sysuptime.days) Days, $($sysuptime.hours) Hours, $($sysuptime.minutes) Minutes, $($sysuptime.seconds) Seconds"
write-host $uptime

答案 1 :(得分:0)

您很可能从第一行获得null。就像Arco444在他的评论中所示,你告诉命令,如果它没有通知你并继续处理。如果失败,则$lastboottime将为$ null。如果你故意放入$null,你可能会收到类似的错误。

System.DirectoryServices.dll[System.Management.ManagementDateTimeconverter]::ToDateTime($null)
  

System.DirectoryServices.dll程序[System.Management.ManagementDateTimeconverter] :: ToDateTime   : 术语   ' System.DirectoryServices.dll程序[System.Management.ManagementDateTimeconverter] :: ToDateTime'   不被识别为cmdlet,函数,脚本文件或的名称   可操作程序。检查名称的拼写,或路径是否正确   包含,验证路径是否正确,然后重试。在线:1   焦炭:1   + System.DirectoryServices.dll [System.Management.ManagementDateTimeconverter] :: ToD   ...   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:ObjectNotFound:(System.Director ... er] :: ToDateTime:String)[],   CommandNotFoundException       + FullyQualifiedErrorId:CommandNotFoundException

一个简单的if将检查变量中是否存在数据。 $uptime值也会反映出来。

$lastboottime = (Get-WMIObject -Class Win32_OperatingSystem -ComputerName     $server -Credential $altcreds -ErrorAction SilentlyContinue).LastBootUpTime
If($lastboottime){
    $sysuptime = (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime)
    $uptime = "   UPTIME           :    $($sysuptime.days) Days, $($sysuptime.hours) Hours, $($sysuptime.minutes) Minutes, $($sysuptime.seconds) Seconds"
} Else {
    $uptime = "   UPTIME           : Unable to determine for host $server"
}