哈希表-按输入顺序排序 [英] Hash Table - Sort in order of how they are input

查看:452
本文介绍了哈希表-按输入顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个哈希表,最终将其输出到Excel电子表格,但是问题似乎是系统默认情况下对哈希表进行排序的方式.我希望它以输入时的顺序返回机器,它们当前的工作方式是弹出一个框,然后粘贴所有机器名,以便它们全部在foreach循环之前存储在内存中.我以前是按照最长的正常运行时间来进行排序的,但是现在需要采用与输入时相同的方式.我最初的想法是创建另一个哈希表,并以与$machineList变量相同的顺序捕获它们,但这甚至可能使我处于同一位置.我尝试搜索,但找不到有关哈希表排序的默认方式的信息.

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.

有什么想法吗?

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

推荐答案

$machineUptime创建为有序哈希表(前提是您具有PowerShell v3或更高版本):

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

$machineUptime = [ordered]@{}

这篇关于哈希表-按输入顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆