Let's suppose that I have a file.properties and its content is:
app.name=Test App
app.version=1.2
...
how can I get the value of app.name?
Let's suppose that I have a file.properties and its content is:
app.name=Test App
app.version=1.2
...
how can I get the value of app.name?
You can use ConvertFrom-StringData to convert Key=Value pairs to a hash table:
$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
If you are running with powershell v2.0 you might be missing the "-Raw" argument for Get-Content. In this case you can use the following.
Content of C:\temp\Data.txt:
environment=Q GRZ
target_site=FSHHPU
Code:
$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'
I wanted to add the solution if you need escaping (for example if you have paths with backslashes):
$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'
Without the -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'
Or in a one-line fashion:
(ConvertFrom-StringData([Regex]::Escape((Get-Content "./app.properties" -raw)) -replace "(\\r)?\\n", [Environment]::NewLine)).'app.name'
I don't know if there is some Powershell integrated way of doing this, but I can do it with regex:
$target = "app.name=Test App
app.version=1.2
..."
$property = "app.name"
$pattern = "(?-s)(?<=$($property)=).+"
$value = $target | sls $pattern | %{$_.Matches} | %{$_.Value}
Write-Host $value
Should print "Test App"