问题
I have a application.properties file in following format
application.name=some thing
application.version=4.1.0.1
application.list=abc.def, ghi.jkl
Now my task is to append mno.pqr to application.list I am able to read it using
$AppProps = convertfrom-stringdata (get-content .\application.properties -raw)
I changed the Application.list
value in $AppProps
.
How to save it back to original Application.properties file..?
回答1:
You can try the following:
$AppProps.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } > .\application.properties
Note that >
creates UTF-16 LE files (with BOM) by default, so if you want to control the encoding explicitly, pipe to either Out-File
or Set-Content
using the -Encoding
parameter instead.
There is no complementary ConvertTo-StringData
, unfortunately, so you have to create your own output formatting (the default output format of a hashtable does not work as a properties file):
ConvertFrom-StringData
returns a hashtable, so$AppProps
contains one.$AppProps.GetEnumerator()
sends the hashtable's key/value pairs (dictionary entries of type[System.Collections.DictionaryEntry]
) one by one through the pipeline.- The
.GetEnumerator()
call is necessary, because PowerShell treats a hashtable as a single object in a pipeline.
- The
% { "$($_.Name)=$($_.Value)" }
constructs the output string for each key/value pair.
Caveats that stem from using ConvertFrom-StringData
to read properties files:
Loss of ordering: Since key ordering is not guaranteed in a hashtable, the properties will typically appear in different order when you rewrite the file (at least the first time).
Loss of comments: Comments in the input file (lines whose first non-blank char. is
#
) are quietly skipped on reading, so you'll lose them when you rewrite the file.
来源:https://stackoverflow.com/questions/35210352/how-to-edit-a-property-file-in-powershell