上次启动时WMI

时间:2014-05-02 03:19:41

标签: powershell wmi

Get-WmiObject win32_operatingsystem -computerName $svr | select csname, @{LABEL='LastBootUpTime';EXPRESSION={($now - $($_.ConverttoDateTime($_.lastbootuptime))).days}} 

这项工作很完美,但我的问题是有没有办法让那些没有进入管道的计算机名称,我的意思是说那些无法访问的计算机或RCP错误或访问被拒绝。?

我想知道是否有任何服务器被关闭或删除。

2 个答案:

答案 0 :(得分:0)

您的示例并未显示您如何输入多个机器名称..但解决方案是这样的,使用try-catch:

$pcs = Get-Content .\list-of-machines.txt
$now = Get-Date

$pcs | ForEach-Object {    
    $pc = $_

    try {
        Get-WmiObject win32_operatingsystem -ComputerName $pc -ErrorAction Stop | ForEach-Object {
            New-Object psobject -Property @{
                MachineName = $pc
                Uptime = ($now - ($_.ConverttoDateTime($_.lastbootuptime))).days
                Result = "SUCCESS"
            }
        }
    } catch {
        New-Object psobject -Property @{
            MachineName = $pc
            Result = $_.Exception.Message
        }
    } 
} |
#Export to CSV
Select MachineName, Uptime, Result | Export-Csv .\Uptime-results.csv -NoTypeInformation

答案 1 :(得分:0)

如果在前端创建对象,可以简化一些代码:

foreach ($srv in $serverlist)
{
  $result = New-Object psobject -Property @{csname=$srv;LastBootUpTime=$null}

  Try {
        $result.LastBootUpTime =
         Get-WmiObject Win32_OperatingSystem -ComputerName $svr  -ErrorAction Stop |
          foreach {($now - $($_.ConverttoDateTime($_.lastbootuptime))).days}
      }

   Catch {$result.LastBootUpTime = $_.Exception.Message}

 $result

}