Powershell解析包含冒号的属性文件

时间:2014-06-10 13:33:26

标签: powershell hashtable properties-file

如果我有一个包含目录(包含冒号)的.properties文件:

some_dir=f:\some\dir\etc
another_dir=d:\dir\some\bin

然后使用ConvertFrom-StringData将Key = Value对从所述属性文件转换为哈希表:

$props_file = Get-Content "F:\dir\etc\props.properties"
$props = ConvertFrom-StringData ($props_file)
$the_dir = $props.'some_dir'
Write-Host $the_dir

Powershell引发错误(不喜欢冒号):

ConvertFrom-StringData : Cannot convert 'System.Object[]' to the type 'System.String'    required by parameter 'StringData'. Specified method is not supported.
At line:3 char:32
+ $props = ConvertFrom-StringData <<<<  ($props_file)
+ CategoryInfo          : InvalidArgument: (:) [ConvertFrom-StringData],     ParameterBindingException
+ FullyQualifiedErrorId :     CannotConvertArgument,Microsoft.PowerShell.Commands.ConvertFromStringDataCommand

你如何绕过这个?我希望能够使用它来引用目录。符号:

$props.'some_dir'

3 个答案:

答案 0 :(得分:10)

冒号与你得到的错误无关。是的,它可以使用ConvertFrom-StringData来实现,但是,正如已经提到的那样,你需要为它提供数组而不是字符串。此外,您需要在文件中使用双反斜杠的路径,因为单个反斜杠被解释为转义字符。

以下是修复代码的方法:

# Reading file as a single string:
$sRawString = Get-Content "F:\dir\etc\props.properties" | Out-String

# The following line of code makes no sense at first glance 
# but it's only because the first '\\' is a regex pattern and the second isn't. )
$sStringToConvert = $sRawString -replace '\\', '\\'

# And now conversion works.
$htProperties = ConvertFrom-StringData $sStringToConvert

$the_dir = $htProperties.'some_dir'
Write-Host $the_dir

答案 1 :(得分:3)

您可以在加载文件时对其进行解析,并逐行填充空哈希表。

$props = @{}
GC "F:\dir\etc\props.properties" | %{$props.add($_.split('=')[0],$_.split('=')[1])}

答案 2 :(得分:2)

ConvertFrom-StringData需要一个字符串,并为它提供一个数组Get-Content cmdlet。将$props_file更改为:

$props_file = (Get-Content "F:\dir\etc\props.properties") | Out-String

你会得到另一个错误:

ConvertFrom-StringData : parsing "f:\some\dir\etc" - Unrecognized escape sequence \s.

你可以像这样绕过它:

$props_file = Get-Content "F:\dir\etc\props.properties"
$props = @{}
$props_file | % {
    $s = $_ -split "="
    $props.Add($s[0],$s[1])
}
$the_dir = $props.'some_dir'
Write-Host $the_dir

结果:

f:\some\dir\etc