Hash Table - Sort in order of how they are input

淺唱寂寞╮ 提交于 2019-12-29 02:00:06

问题


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"
    }
}

回答1:


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

$machineUptime = [ordered]@{}


来源:https://stackoverflow.com/questions/36629439/hash-table-sort-in-order-of-how-they-are-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!