2013-11-28 9 views
20

Załóżmy, że mam file.properties a jego treść jest:Czytaj pliku właściwości w powershell

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

jaki sposób można uzyskać wartość app.name?

+0

można użyć wyrażenia regularnego lub '-split' linie w' = '. –

Odpowiedz

28

Można wykorzystać ConvertFrom- StringData przekonwertować pary klucz = wartość do tabeli mieszania:

$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 
+0

dzięki! Zaimplementowałem mój kod w następujący sposób: $ AppProps = convertfrom-stringdata (get-content ./app.properties -raw) $ AppProps.'client.version ' – jos11

+9

Flaga '-Raw' została dodana w PowerShell 3 Jeśli chcesz użyć tego na PowerShell 2, użyj 'Get-Content $ file | Out-String' zamiast tego. – Koraktor

1

Nie wiem, czy istnieje jakiś PowerShell zintegrowany sposób to zrobić, ale mogę zrobić to z 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 

powinien wypisać „App Test”

7

Jeśli działa z PowerShell v2.0 może być brakuje „-Surowe” argument dla Get-Content. W takim przypadku możesz użyć poniższych.

Zawartość C: \ temp \ DATA.TXT:

środowisko = P GRZ

target_site = FSHHPU

Kod:

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

że chciał dodaj rozwiązanie, jeśli potrzebujesz ucieczki (na przykład, jeśli masz ścieżki z odwróconymi ukośnikami):

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

Bez -Surowe:

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

Albo w sposób jedno-line:

(ConvertFrom-StringData([Regex]::Escape((Get-Content "./app.properties" -raw)) -replace "(\\r)?\\n", [Environment]::NewLine)).'app.name' 
Powiązane problemy