How to find hash key from an array, and update the array based on the key of the hash using powershell?

Mike 251 Reputation points
2021-03-07T12:57:44.72+00:00

I really have been research and fell short on where to start on this.

My objective is to find the value in my hashtable from an existing array. and if it existis, wanted to updated the $array. really stuck and need some help to give me some example that I can learn upon.

populating my hash from csv.
$hash = @{ }
import-csv data.csv | foreach {hash.add($_tSamaccountname,gSamaccountname)
this imports a name mike and key michael

then i have an $array that contains mike,mark.
how do I loop thru this array looking if the value is in my $hash, then update the array from the key.

So my $array should now be michael,mark.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2021-03-08T04:26:07.237+00:00

    Replace line #1 in the code below to load the hash with your CSV.

    $x= [PSCustomObject]@{tSamaccountname='mike';gSamaccountname='michael'}, [PSCustomObject]@{tSamaccountname='mark';gSamaccountname='marcus'}
    [System.Collections.ArrayList]$a = @('mike','mark')
    $h = @{}
    $x |
        ForEach-Object{
            $h.($_.tSamaccountname) = $_.gSamaccountname
        }
    for ($i =0; $i -lt $a.count; $i++){
            if ($h.ContainsKey($a[$i])){
                $a.item($i) = $h.($a[$i])
            }
    }
    $a
    

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2021-03-08T03:58:02.933+00:00

    Hi,

    If the tSamaccountname is mike and the gSamaccountname is michael, you can update the array like this

    $hash = @{ }  
    import-csv d:\temp\data.csv | foreach {  
    $hash.add($_.tSamaccountname,$_.gSamaccountname)  
    }  
    $array = 'mike','mark'  
    for($i=0; $i -lt $array.count; $i++){  
       if($hash.($array[$i])){  
            $array[$i] = $hash.($array[$i])  
        }  
    }  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.