Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell hashtable problem

I am trying to read a config file which has some key value pairs as shown below:

age = 7
server = \\server\
destination = \\nas\public\server\

Here is the script I am using to read the file:

gc "keyval.txt" | % -begin {$h=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $h.Add($k[0], $k[1]) } }
$h                    #THIS PRINTS THE KEYS and VALUES
$h.get_item("server") #THIS DOESN'T DO ANYTHING
$h.server             #THIS DOESNT DO ANYTHING AS WELL

I learnt that there are some oddities with hashtables in powershell, but could not get a hold on the way to avoid the oddities. Please help me resolve this issue.

like image 508
Animesh Avatar asked Nov 17 '25 05:11

Animesh


1 Answers

If you don't want to modify the file:

$re = '\s*(\w+)\s*=\s*(\S+)'
Get-Content \temp\foo.txt | 
  Foreach {$ht=@{}} {if ($_ -match $re) {$ht.($matches[1]) = $matches[2]}} {$ht}

Name                           Value
----                           -----
age                            7
server                         \\server\
destination                    \\nas\public\server\
like image 79
Keith Hill Avatar answered Nov 18 '25 20:11

Keith Hill



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!