-
- PowerShell将配置文件转换为字典(hash table)
- 2012-11-10
标准的*nix下的配置文件一般是如下的标准格式
#this is a test conf file [SectionName1] name=abc id=123 [dbinfo] db=localhost name=testdb user=root
因此我们在很多应用时也采用这种方式,简单易理解,维护也方便,但是在程序用需要将里面的内容转化为程序能使用的更高效的字典才能真正发挥作用,如果是python的话,可以直接用configParser,
而对于Windows上使用的PowerShell,这种“外来”的和尚,想要能念得起经,还是要自己动手的
function global:Conf2Dict{ param([string]$confFile) if(test-path $confFile -pathType Leaf) { $dict= @{} foreach ($line in (Get-Content $confFile)) { $lin = $line.Trim() if(!$lin.startsWith("#") -and $lin -ne ($null -or "")) { if($lin -Match "^\[\w+\]$" -and $lin.Length -gt 2){ $k = $lin.Substring(1,$lin.Length-2) $dict[$k] = @{} }else{ $arrPath = $lin.Split("=") $nam = $arrPath[0].Trim() $var = $arrPath[1].Trim() $dict[$k][$nam] = $var } } } if($dict.Count -ge 1){ return $dict }else{ return $null } }else{ return $null } }
-
Views(5994) | Comments(0) |
In:
System/Application
|

生活中心
(02/19)
