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

ar.*_*dll 5 powershell hashtable properties-file

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

some_dir=f:\some\dir\etc
another_dir=d:\dir\some\bin
Run Code Online (Sandbox Code Playgroud)

然后使用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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

你怎么绕这个?我希望能够使用它来引用目录.符号:

$props.'some_dir'
Run Code Online (Sandbox Code Playgroud)

Ale*_*sht 11

冒号与你得到的错误无关.是的,它可以使用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
Run Code Online (Sandbox Code Playgroud)