Sorting results from foreach

The below works and writes the output to the console. I can’t figure out how to sort the results on LastBoot once it completes.

I tried $Obj | sort LastBoot

Also tried $report += $object then $report | sort LastBoot

 

 

Function Get-Uptime {

[CmdletBinding()]

Param (
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]

[string[]]$ComputerName, 
[Switch]$ErrorLog,
[string]$Logfile = 'c:\it\errorlog.txt',
[Switch]$OU

)

if ($ou.IsPresent) {

$oulist = Get-ADOrganizationalUnit -filter * | select DistinguishedName | Out-GridView -PassThru | Select-Object -ExpandProperty DistinguishedName
$computers = Get-ADComputer -filter * -Properties * -SearchBase $oulist | select name -ExpandProperty name

Foreach ($Computer in $computers) {
Try{
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop -ErrorVariable CurrentError
$Uptime = (Get-Date) - $OS.ConvertToDateTime($OS.LastBootUpTime)

$Properties = @{ComputerName = $Computer
LastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
Uptime = ([String]$Uptime.Days + " Days " + $Uptime.Hours + " Hours " + $Uptime.Minutes + " Minutes")
}

$Obj = New-Object -TypeName PSObject -Property $Properties | Select ComputerName, LastBoot, UpTime

$obj


} 
catch{

Write-Warning "An error occured on $Computer"
if ($ErrorLog) {
Get-Date | Out-File $LogFile -Append
$Computer | Out-File $LogFile -Append
$CurrentError | out-file $LogFile -Append
}

} 
}


}

}
Foreach ($Computer in $computers) {
Try{
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop -ErrorVariable CurrentError
$Uptime = (Get-Date) - $OS.ConvertToDateTime($OS.LastBootUpTime)

$Properties = @{ComputerName = $Computer
LastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
Uptime = ([String]$Uptime.Days + " Days " + $Uptime.Hours + " Hours " + $Uptime.Minutes + " Minutes")
}

$Obj = New-Object -TypeName PSObject -Property $Properties | Select ComputerName, LastBoot, UpTime

$Obj

[Array]$objs+=$Obj #Add it
}
catch{

Write-Warning "An error occured on $Computer"
if ($ErrorLog) {
Get-Date | Out-File $LogFile -Append
$Computer | Out-File $LogFile -Append
$CurrentError | out-file $LogFile -Append
}

}
}

$Objs |Sort-Object LastBoot #Add it

}

PSObject has an [ordered] type accelerator that will order your table by the order in which you give it properties. Alternately, [PSCustomObject] does this for you by default as well.

Also I formatted your ‘Uptime’ property with the more flexible ‘-f’ string operator :slight_smile:

Try this:

[pre]
$Properties = [PSCustomObject]@{
ComputerName = $Computer
LastBoot = $OS.ConvertToDateTime($OS.LastBootUpTime)
Uptime = “{0} Days {1} Hours {2} Minutes” -f $uptime.Days,$Uptime.Minutes,$Uptime.Hours
}
[/pre]

Produces:

[pre]
PS C:\Users\nate> $properties | Format-List

ComputerName : localhost
LastBoot : 4/13/2019 8:55:00 AM
Uptime : 5 Days 7 Hours 2 Minutes
[/pre]