【发布时间】:2013-12-15 01:06:25
【问题描述】:
假设我有一个 file.properties,它的内容是:
app.name=Test App
app.version=1.2
...
如何获取 app.name 的值?
【问题讨论】:
-
您可以使用正则表达式或
-split=处的行。
标签: powershell properties-file
假设我有一个 file.properties,它的内容是:
app.name=Test App
app.version=1.2
...
如何获取 app.name 的值?
【问题讨论】:
-split = 处的行。
标签: powershell properties-file
您可以使用 ConvertFrom-StringData 将 Key=Value 对转换为哈希表:
$filedata = @'
app.name=Test App
app.version=1.2
'@
$filedata | set-content appdata.txt
$AppProps = convertfrom-stringdata (get-content ./appdata.txt -raw)
$AppProps
Name Value
---- -----
app.version 1.2
app.name Test App
$AppProps.'app.version'
1.2
【讨论】:
-Raw 标志已添加到 PowerShell 3 中。如果您想在 PowerShell 2 上使用此标志,请改用 Get-Content $file | Out-String。
如果您使用 powershell v2.0 运行,您可能会缺少 Get-Content 的“-Raw”参数。在这种情况下,您可以使用以下内容。
C:\temp\Data.txt 的内容:
环境=Q GRZ
target_site=FSHHPU
代码:
$file_content = Get-Content "C:\temp\Data.txt"
$file_content = $file_content -join [Environment]::NewLine
$configuration = ConvertFrom-StringData($file_content)
$environment = $configuration.'environment'
$target_site = $configuration.'target_site'
【讨论】:
如果您需要转义(例如,如果您有带反斜杠的路径),我想添加解决方案:
$file_content = Get-Content "./app.properties" -raw
$file_content = [Regex]::Escape($file_content)
$file_content = $file_content -replace "(\\r)?\\n", [Environment]::NewLine
$configuration = ConvertFrom-StringData($file_content)
$configuration.'app.name'
没有 -raw:
$file_content = Get-Content "./app.properties"
$file_content = [Regex]::Escape($file_content -join "`n")
$file_content = $file_content -replace "\\n", [Environment]::NewLine
$configuration = ConvertFrom-StringData($file_content)
$configuration.'app.name'
或者以单行方式:
(ConvertFrom-StringData([Regex]::Escape((Get-Content "./app.properties" -raw)) -replace "(\\r)?\\n", [Environment]::NewLine)).'app.name'
【讨论】:
Get-Content 似乎在我的系统(Windows 10.0.17134.765)上自动处理任一行结尾。
我不知道是否有一些 Powershell 集成方式可以做到这一点,但我可以用正则表达式做到这一点:
$target = "app.name=Test App
app.version=1.2
..."
$property = "app.name"
$pattern = "(?-s)(?<=$($property)=).+"
$value = $target | sls $pattern | %{$_.Matches} | %{$_.Value}
Write-Host $value
应该打印“测试应用”
【讨论】: