PowerShell hash table problem

I tried to read a configuration file containing some key value pairs, as follows:

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

This is the script I use 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've learned that there are some strange hash tables in PowerShell, but I can't avoid the tricky methods Please help me solve this problem

Solution

If you do not 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\
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>