Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash Table - Sort in order of how they are input

I have a hash table here and I have it eventually outputting to an Excel spreadsheet, but the issue appears to be the way the system sorts the hash table by default. I want it to return the machines in the same order that they are inputted, they way it currently works is a box pops up and you paste in all your machine names so they are all in memory prior to the foreach loop. I was previously sorting this by the longest uptime but it now needs to be the same way they are inputted. My initial thought is to create another hash table and capture them in the same order versus the $machineList variable, but that might even leave me in the same position. I tried to search but I couldn't find info on the default way that hash tables sort.

Any ideas?

$machineUptime = @{}
foreach($machine in $machineList){
    if(Test-Connection $machine -Count 1 -Quiet){
        try{
            $logonUser = #gets the logged on user
            $systemUptime = #gets the wmi property for uptime

            if($logonUser -eq $null){
                $logonUser = "No Users Logged on"
            }

            $machineUptime[$machine] = "$systemUptime - $logonUser"
        }
        catch{
            Write-Error $_
            $machineUptime[$machine] = "Error retrieving uptime"
        }
    }
    else{
        $machineUptime[$machine] = "Offline"
    }
}
like image 231
nkasco Avatar asked Sep 13 '25 05:09

nkasco


1 Answers

Create $machineUptime as an ordered hashtable (provided you have PowerShell v3 or newer):

$machineUptime = [ordered]@{}
like image 152
Ansgar Wiechers Avatar answered Sep 14 '25 19:09

Ansgar Wiechers