Home > Blockchain >  How to do ForEach only on objects in hashtable that match object in array
How to do ForEach only on objects in hashtable that match object in array

Time:07-03

I have a hashtable used in a job, each hash.key is a job name:

$myhashtable = @{ 
    'somelocation'    = 'somevalue'
    'otherlocation'   = 'othervalue'
}

I run the hashtable against a function, the function is a Start-Job that runs for each object in the hashtable.

foreach ( $location in $myhashtable.GetEnumerator() )
{
    SomeFunction
}

I then get the names of stopped jobs:

$joblist = Get-Job | Where-Object { $_.State -eq "Stopped" }
$joblist = $joblist.name

Trying to do the same as above against the function but only for the jobs that have stopped:

foreach( $location in $myhashtable.GetEnumerator() )
{
    if $location.key matches an object in $joblist}( 
    do SomeFunction for those $location.keys)
}

I've tried various foreach if and where but can't hit on it.

Thanks!

CodePudding user response:

as @zett42 noted, your question uses which you name $Array. Renaming this in my reply to avoid confusion, but I think the code below will do what you are trying to do.

PS> $myHashtable = @{
>> 'key1'   = 'value1'
>> 'key2'   = 'value2'
>> 'key3'   = 'value3'
>> }
PS> $joblist= 'key1', 'key2'
PS> $myHashtable.keys | ForEach-Object { if( $_ -in $joblist ){ $myHashtable[$_] } }
value1
value3

CodePudding user response:

Here is a possible solution:

$myhashtable = @{ 
'somelocation'    = 'somevalue'
'otherlocation'   = 'othervalue'
}

# For each job that has stopped and whose name matches a key in $myhashtable
Get-Job | Where-Object { $_.State -eq Stopped -and $myhashtable.Contains( $_.Name ) } | 
    ForEach-Object {
        SomeFunction 
    }

When you have a hashtable, you normally shouldn't loop over it, to search for a key somewhere else, which is very inefficient. Instead do it the other way around, loop over the array of objects you want to match and do a lookup in the hashtable, e.g. by calling the .Contains method or using the index operator []. The .Contains method returns $true if the given argument matches one of the keys of the hashtable. This is a very efficient operation, because a hashtable is optimized for fast lookup of keys.

  • Related