在powershell中读取属性文件

问题描述 投票:24回答:4

假设我有一个file.properties,其内容是:

app.name=Test App
app.version=1.2
...

我怎样才能获得app.name的值?

powershell properties-file
4个回答
39
投票

您可以使用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

10
投票

如果您使用的是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'

3
投票

如果您需要转义,我想添加解决方案(例如,如果您有带反斜杠的路径):

$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'

1
投票

我不知道是否有一些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

应该打印“测试应用程序”

© www.soinside.com 2019 - 2024. All rights reserved.