在powershell中读取属性文件

jos*_*s11 26 powershell properties-file

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

app.name=Test App
app.version=1.2
...
Run Code Online (Sandbox Code Playgroud)

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

mjo*_*nor 42

您可以使用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
Run Code Online (Sandbox Code Playgroud)

  • PowerShell 3中添加了`-Raw`标志.如果要在PowerShell 2上使用它,请使用`Get-Content $ file | Out-String`代替. (9认同)

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


小智 5

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

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

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

或者以单行方式:

(ConvertFrom-StringData([Regex]::Escape((Get-Content "./app.properties" -raw)) -replace "(\\r)?\\n", [Environment]::NewLine)).'app.name'
Run Code Online (Sandbox Code Playgroud)