简体   繁体   English

哈希表PowerShell

[英]Hash table PowerShell

I need some help to eliminate duplicate entries in a hashtable. 我需要一些帮助来消除哈希表中的重复条目。

Code: 码:

$username=Get-Content ".\u.txt"
#$username
$fileread=Get-Content ".\lastlogon.txt"
$lastinfo=$fileread|select-string -pattern "logged off" -encoding ASCII
foreach($i in $lastinfo){
    $splitinfo=$i -split("Login ID: ")
    $dateinfo=$splitinfo[0] -split("       ")
    $finaldateinfo=$dateinfo[2] -split(" ")
    #$finaldateinfo[0]
    $userinfo=$splitinfo[1] -split(" ")
    #$userinfo[0]
    $hashinfo= @{$userinfo[0]=$finaldateinfo[0]}
    #$hashinfo
    foreach($h in $hashinfo.GetEnumerator()){
        foreach($a in $username){
            if($hashinfo.ContainsKey($a)){
                "$($hashinfo.keys):$($hashinfo.Values)"
            }
        }
    }
}

Result: 结果:

Name      Value
----     -----
USERID 08/03/2018
USERID 09/03/2018
USERID 10/03/2018
USERID 13/03/2018
ADM 23/03/2018

The hashtable is like this. 哈希表是这样的。

I need only the last entry of USERID to be kept and eliminate all the other values of USERID. 我只需要保留USERID的最后一个条目,并消除USERID的所有其他值。

This can't be a hashtable. 这不能是哈希表。 As far as I know there can't be any duplicate keys (Name) in a hashtable as that's the purpose of the hashtable - to return values based on unique keys. 据我所知,哈希表中不能有任何重复的键(名称),因为这是哈希表的目的-基于唯一键返回值。 Please recheck. 请重新检查。

If this is an array then, 如果这是一个数组,

$lastmatch = $arr | where { $_.Name -match "USERID" } | select -Last 1

Add the above result to a hashtable like, 将以上结果添加到哈希表中,例如:

$ht.Add($lastmatch.Name,$lastmatch.Value)

I'm a little rusty in Powershell, but I believe you can create a dictionary (hash table) like this: 我对Powershell有点生疏,但我相信您可以像这样创建字典(哈希表):

$LastAccessByUser= @{}

Assuming your source data is already ordered, simple iterate over it. 假设您的源数据已订购,则对其进行简单的迭代。 I don't know your variable names, so I'll just provide an example assuming you have a list by the name $list containing Items. 我不知道您的变量名称,因此我仅提供一个示例,假设您有一个名为$ list的列表,其中包含Items。

foreach ($item in $list.Items)
{
    $LastAccessByUser[$item.Name] = $item.Value
}

Apologies if it doesn't quite match your scenario, but you should be able to adjust based on what you have. 抱歉,如果它与您的情况不太匹配,但是您应该能够根据自己的情况进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM