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

Mike 246 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 Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,364 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 44,776 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. Ian Xue (Shanghai Wicresoft Co., Ltd.) 29,651 Reputation points Microsoft Vendor
    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.