Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick File to Hashtable in PowerShell

Given an array of key-value pairs (for example read in through ConvertFrom-StringData), is there a streamlined way of turning this into a Hashtable or similar to allow quick lookup? I.e. a way not requiring me to loop through the array and manually build up the hashtable myself.

Example data

10.0.0.1=alice.example.com
10.0.0.2=bob.example.com

Example usage

$names = gc .\data.txt | ConvertFrom-StringData
// $names is now Object[]
$map = ?
// $map should now be Hashtable or equivalent
echo $map['10.0.0.2'] 
// Output should be bob.example.com

Basically what I'm looking for is a, preferably, built-in file-to-hashtable function. Or an array-to-hashtable function.


Note: As @mjolnior explained, I actually got hash tables, but an array of single value ones. So this was fixed by reading the file -raw and hence didn't require any array to hashtable conversion. Updated the question title to match that.

like image 532
Svish Avatar asked Sep 11 '26 15:09

Svish


1 Answers

Convertfrom-Stringdata does create a hash table.

You need to give it the key-value pairs as a single multi-line string (not a string array)

$map = Get-Content -raw .\data.txt | ConvertFrom-StringData

$map['10.0.0.2']

bob.example.com

When you use Get-Content without the -Raw switch, you're giving ConvertFrom-StringData an array of single-line strings, and it's giving you back an array of single-element hash tables:

$map = Get-Content .\data.txt | ConvertFrom-StringData

$map.gettype()

$Map[0].GetType()

$map[0]



IsPublic IsSerial Name                                     BaseType                                                                   
-------- -------- ----                                     --------                                                                   
True     True     Object[]                                 System.Array                                                               
True     True     Hashtable                                System.Object                                                              

Key   : 10.0.0.1
Value : alice.example.com
Name  : 10.0.0.1
like image 129
mjolinor Avatar answered Sep 14 '26 12:09

mjolinor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!