Search code examples
powershellhashtable

Not able to get values from HashTable in Powershell


I am new to Powershell. I have written a query and I am getting two columns from the query. What I want is Key = Col1 and Value = Col2. I am able to print the whole Hashtable, but I am not able to get the value in the format Col1['Col2] = x. Below is my code:

$query1 = "select top 5 Col1, Col2 from TableName"
$databases1 = Invoke-Sqlcmd -Query $query1 -ConnectionString "ConnectionString"    
$hash = @{$databases1.Col1 = $databases1.Col2}
return $hash

The variable $hash returns as below:

Name                Value                                                                                                                                                                                           
----                -----                                                                                                                                                                                           
{a, b, c,...{1, 2, 3, 4...} 

But I want to access it as $hash['a'] = 1 Can anyone please help me out?


Solution

  • You must enumerate the rows returned by your query and create an entry in the target hashtable for each:

    $hash = [ordered] @{} # initialize the (ordered) hashtable
    $databases1 | ForEach-Object {
      $hash[$_.Col1] = $_.Col2
    }