【问题标题】:Read a properties file in powershell在 powershell 中读取属性文件
【发布时间】:2013-12-15 01:06:25
【问题描述】:

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

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

如何获取 app.name 的值?

【问题讨论】:

  • 您可以使用正则表达式或-split = 处的行。

标签: powershell properties-file


【解决方案1】:

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

【讨论】:

  • 谢谢!!!我的代码实现如下: $AppProps = convertfrom-stringdata (get-content ./app.properties -raw) $AppProps.'client.version'
  • -Raw 标志已添加到 PowerShell 3 中。如果您想在 PowerShell 2 上使用此标志,请改用 Get-Content $file | Out-String
【解决方案2】:

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

    【讨论】:

    • 这正是我的问题!感谢您添加此内容。
    • 为什么正则表达式转义和手动规范化的行尾? Get-Content 似乎在我的系统(Windows 10.0.17134.765)上自动处理任一行结尾。
    【解决方案4】:

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

    应该打印“测试应用”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-26
      • 2013-01-20
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多