1

我有以下脚本可以找到计算机列表的最后重新启动时间。当我运行这个脚本时,它将第一台计算机名放在一行,但时间戳在第二行。随后的计算机都在同一条线上。

这是示例:

Computer1  
TimeStamp  
Computer2 TimeStamp  
Computer3 TimeStamp

ETC...

我希望它是这样的:

Computer1 TimeStamp  
Computer2 TimeStamp  
Computer3 TimeStamp

我究竟做错了什么?

这是代码:

$listOfComputers = Import-Csv lastReboot.txt
ForEach($computer in $listOfComputers) {
  $name = $computer.Name
  Write-Host $name -NoNewLine
  $wmi = Get-WmiObject -Class Win32_OperatingSystem -Computer $name
  $wmi.ConvertToDateTime($wmi.LastBootUpTime)
}
4

2 回答 2

3

您为输出混合了 write-host 和 out-default,这通常会导致项目以错误的顺序显示和其他格式问题:

尝试:

$listOfComputers = IMPORT-CSV lastReboot.txt
ForEach($computer in $listOfComputers){
$name = $computer.Name
Write-Host "$name " -NoNewLine
$wmi = Get-WmiObject -Class Win32_OperatingSystem -Computer $name
write-host $wmi.ConvertToDateTime($wmi.LastBootUpTime)
}
于 2013-10-04T18:13:26.637 回答
1

当您使用-computernamewith 时get-wmiobject,您会在结果中获得一个额外的字段 - PSComputerName。您可以选择该字段,以便轻松获得与其他数据相关的名称。

将此与 中的表达式结合起来select-object,您将得到一张漂亮的表格。但是等等 - 还有更多!

Get-WMIObject可以为参数取一个名称数组-computername,完全不需要循环。

$listOfComputers = IMPORT-CSV r:\lastReboot.txt
$wmi = Get-WmiObject -Class Win32_OperatingSystem -Computer $listOfComputers.Name;
$wmi |select pscomputername,@{Name="LastBootTime";Expression={$_.converttodatetime($_.lastbootuptime);}};

我们还可以消除$wmi变量并在一个管道中完成所有操作(为清楚起见添加了换行符)。

$listOfComputers = IMPORT-CSV r:\lastReboot.txt
Get-WmiObject -Class Win32_OperatingSystem -Computer $listOfComputers.Name |`
    select-object pscomputername,@{Name="LastBootTime";Expression={$_.converttodatetime($_.lastbootuptime);}};

甚至可以一次性完成整个导入、查询和输出:

IMPORT-CSV r:\lastReboot.txt |`
    select-object -ExpandProperty name |`
    foreach-object{ Get-WmiObject -Class Win32_OperatingSystem -Computer $_} |`
    select-object pscomputername,@{Name="LastBootTime";Expression={$_.converttodatetime($_.lastbootuptime);}};

如果您需要保留数据以供以后使用,您可以将其分配给$wmi =最后两个示例中任一示例开头的变量(确切地说,是第一个示例中的第二行)。

编辑:我只记得 AliasPropertyPSComputerName是在 v3 中添加的(或在 v2 中被破坏)。因此,如果您使用的是 v2,则需要__SERVER改用。

于 2013-10-04T18:08:28.347 回答