想用PowerShell查询远程PC的正常运行时间

时间:2017-01-10 15:29:09

标签: powershell wmic

我想查询机器的正常运行时间,并决定通过PowerShell尝试这个,但我很难让它运行起来。这是我到目前为止所做的:

   function Get-PCUptime {

        param (
            [Parameter(ValueFromPipeline=$true)]
            [String]$computer  = (Read-Host "Enter a computer name")
        )


        $lastboottime = (Get-WmiObject -Class Win32_OperatingSystem -Credential Administrator -comp $computer)
        $sysuptime = (Get-Date) – [System.Management.ManagementDateTimeconverter]::ToDateTime($lastboottime.LastBootUpTime)

        if ($lastboottime -ne $NULL){
            Write-Host “System($computer) is Uptime since : ” $sysuptime.days “days” $sysuptime.hours `
            “hours” $sysuptime.minutes “minutes” $sysuptime.seconds “seconds” -Foregroundcolor Gray;
        } 
    }

我似乎无法使其正常工作,因为我想将其转换为天,小时,分钟等。

这是我收到的错误:

  

异常调用" ToDateTime"用" 1"参数:"指定的参数超出了有效值的范围。   参数名称:dmtfDate"

1 个答案:

答案 0 :(得分:3)

您可以在ConvertToDateTime

上使用Win32_OperatingSystem方法
function Get-PCUptime {
    param (
        [Parameter(ValueFromPipeline=$true,
                   HelpMessage="Enter a Computer Name"
        )]
        [String]$computer
    )

    $OS = (Get-WmiObject -Class Win32_OperatingSystem -Credential Administrator -comp $computer)
    $sysuptime = (Get-Date) – ($OS.ConvertToDateTime($OS.LastBootUpTime))

    if ($OS -ne $NULL){
        Write-Host “System($computer) is Uptime since : ” $sysuptime.days “days” $sysuptime.hours `
        “hours” $sysuptime.minutes “minutes” $sysuptime.seconds “seconds” -Foregroundcolor Gray;
    } 
}