在 Powershell 中检查远程服务器的正常运行时间

Checking UPTIME of remote server in Powershell

我正在尝试使用脚本中的以下代码片段检索远程服务器的正常运行时间。

$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"

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

谢谢!

将 WMI 对象上的时间值转换为日期时间对象可以通过调用对象本身的方法 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

您很可能从第一行得到一个空值。就像 Arco444 在他的评论中显示的那样,您是在告诉命令,如果失败则不通知您并继续处理。如果失败,$lastboottime 将是 $null。如果你故意输入 $null,你可能会得到类似的错误。

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

System.DirectoryServices.dll[System.Management.ManagementDateTimeconverter]::ToDateTime : The term 'System.DirectoryServices.dll[System.Management.ManagementDateTimeconverter]::ToDateTime' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char: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"
}