Talk:PowerShell/Arrays and Hash Tables

From Wikiversity
Jump to navigation Jump to search

Resource Page Discussion[edit]

Use Add topic above to add a topic for discussion. Sign your edits using the Signature and timestamp button or by typing ~~~~.

You can also create / amend a hash table like so...[edit]

   $Hash = @{ }
   $Hash | % { $_.Name1 = 1 ; $_.Name2 = 2 ; $_.Name3 = 3 }

There are some other ways to make them as well, like Add-Member... or Group-Object -AsHashTable ...

But the method I've shown above helps if you want to do something like this...

Setting up an array to use as an index. ( Nested array here too btw ) ````

   $Colors = @( 'black' , 'blue' , 'cyan' ; @( 'blue' , 'cyan' , 'gray' , 'green' , 'magenta' , 'red' , 'yellow' | % { "dark$_" } ) + 'gray' , 'green' , 'magenta' , 'red' , 'white' , 'yellow' )
   $Hash = [ Ordered ]@{ }
   $Hash | % { ForEach ( $i in 0..15 ) { $_.Add( "$i" , "$( $colors[$i] )") } }

What this does is creates a hash table with 15 objects, in order, with the color above corresponding to the correct # in the table.

You can use this to further nest other hash tables, or arrays, or multidimensional arrays or additional loops, or just some static strings.

Lets say you wanted to get some things out of an object selection...

   $Hash = [ Ordered ]@{ }
   $Adapters = Get-NetIPInterFace | Select InterfaceAlias , AddressFamily
   $Count = $Adapters.Count - 1
   $Hash | % { ForEach ( $i in 0..$Count ) { $_.Add( "[$I] $( $Adapters.InterfaceAlias[$i] )" , "$( $Adapters.AddressFamily[$i] )" ) } }

Now you can start to understand that there's some practical use case scenarios for trying to get things into a list like this. You could use the 2nd line here, $Adapters, and that will print out a similar list, however, if you need to select an item based on other matching criteria, then it helps to have an index number that way you can always refer back to the same object in the pipeline.

-MC Mcc85s (discusscontribs) 08:58, 22 August 2019 (UTC)