powershell哈希表问题
我正在尝试读取一个配置文件,其中包含一些键值对,如下所示:
age = 7
server = \\server\
destination = \\nas\public\server\
这是我用来读取该文件的脚本:
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
我了解到 powershell 中的哈希表存在一些奇怪之处,但无法掌握避免奇怪现象的方法。请帮我解决这个问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不想修改该文件:
If you don't want to modify the file:
首先修改你的txt以应用我要教你的方法。地下值部分的每个字符串都必须通过 C# 解释,因此像 \s 或 \p 这样的东西是不好的,因为它们没有任何意义。因此,要使用反斜杠,您需要使用反斜杠对其进行转义,例如 \\\\ 表示两个反斜杠。修复文件后,您必须读取文件的所有内容并应用convertfrom-stringdata cmdlet。这是代码,享受吧。
PD:修改文件一行
first modify your txt to apply the method i'm going to teach you. Underground every string of the values part must be pass the c# interpretation so things like \s or \p are bad because they don't mean anything. So to have a backslash you need to escape it with backslash, example \\\\ means two backslash. After fix the file you must read all the content of the file and apply the convertfrom-stringdata cmdlet. Here is the code, enjoy.
PD: modify the file is one line