Incorrect foreach loop for complex vocabulary

I am using Windows 7 editor and PowerGUI Script to write ps1. Here is part of my codes:

#In global scope $Type_Trans = "System.Collections.Generic.Dictionary[System.String,PSObject]" $Type_Farms = "System.Collections.Generic.Dictionary[System.Int32,$Type_Trans]" $Dic_Counts = New-Object $Type_Farms #...puts some data in $Dic_Counts here... #It is no problem with printing out it in console #Now call the function below Write-Data $Dic_Counts Function Write-Data { param( $Dic_Counts ) Foreach($Dic_CountsSingle in $Dic_Counts) { Write-DataSingle $Dic_CountsSingle #THIS LINE! } } 

It is very strange here: why is Dic_CountsSingle not a KeyValuePair , but is it exactly the same as Dic_Counts ??

Many thanks!

+4
source share
3 answers

Using

 foreach ($Dic_CountsSingle in $DicCounts.GetEnumerator()) 

The same goes for hashtables in PowerShell, so it’s not particularly surprising.

+10
source

I do it like this:

 $Dic_Counts.keys | %{ $Dic_Counts[$_] } 
+7
source

I think it broke here:

 Foreach($Dic_CountsSingle in $Dic_Counts) 

This foreach loop expects an array as the second argument. $ Dic_Counts is a hash table, so it has no index. Now I am wondering if an ordered hash table will work in a foreach loop. It has an index.

Nope. Foreach will also not list an ordered hash table. Gotta do it myself.

0
source

Source: https://habr.com/ru/post/1403057/


All Articles