Reputation: 261
I have the following script that finds the last reboot time of a list of computers. When I run this script, it puts the first computer name on a line, but the timestamp is on the second line. Subsequent computers are all on the same line.
Here is the example:
Computer1
TimeStamp
Computer2 TimeStamp
Computer3 TimeStamp
etc...
I want it to be this:
Computer1 TimeStamp
Computer2 TimeStamp
Computer3 TimeStamp
What am I doing wrong?
Here is the code:
$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)
}
Upvotes: 1
Views: 894
Reputation: 28194
When you use -computername
with get-wmiobject
, you get an additional field in the results - PSComputerName
. You can select that field so that you get the name correlated to the other data easily.
Combine this with an expression in select-object
, and you get a nice table. But wait - there's more!
Get-WMIObject
can take an array of names for the -computername
parameter, eliminating the need for your loop altogether.
$listOfComputers = IMPORT-CSV r:\lastReboot.txt
$wmi = Get-WmiObject -Class Win32_OperatingSystem -Computer $listOfComputers.Name;
$wmi |select pscomputername,@{Name="LastBootTime";Expression={$_.converttodatetime($_.lastbootuptime);}};
We can also eliminate the $wmi
variable and do it all in one pipeline (linebreak added for clarity).
$listOfComputers = IMPORT-CSV r:\lastReboot.txt
Get-WmiObject -Class Win32_OperatingSystem -Computer $listOfComputers.Name |`
select-object pscomputername,@{Name="LastBootTime";Expression={$_.converttodatetime($_.lastbootuptime);}};
Or even do the whole import, query & output in a single shot:
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);}};
If you need to keep the data for use later, you can assign that to a variable with $wmi =
at the beginning of either of the last 2 examples (second line in the first example, to be exact).
Edit: I just remembered that the AliasProperty PSComputerName
was added in v3 (or is broken in v2). So if you're using v2, you'll need to use __SERVER
instead.
Upvotes: 1
Reputation: 16646
You're mixing write-host and out-default for your output which will often result in items being displayed in the wrong sequence and other formatting problems:
Try:
$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)
}
Upvotes: 3