gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:34:17 24 4
gpt4 key购买 nike

如果我有一个包含目录(包含冒号)的 .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'

最佳答案

冒号与您得到的错误无关。是的,它可以使用 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

关于Powershell 解析包含冒号的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24142436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com