如何在 powershell 中编辑 .property 文件 [英] How to edit a .property file in powershell

查看:121
本文介绍了如何在 powershell 中编辑 .property 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式如下的 application.properties 文件

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

现在我的任务是将 mno.pqr 附加到 application.list我可以使用

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)

我更改了 $AppProps 中的 Application.list 值.如何将其保存回原来的 Application.properties 文件..?

I changed the Application.list value in $AppProps. How to save it back to original Application.properties file..?

推荐答案

您可以尝试以下操作:

$AppProps.GetEnumerator() | % { "$($_.Name)=$($_.Value)" } > .\application.properties

注意 > 默认创建 UTF-16 LE 文件(带 BOM),所以如果你想明确控制编码,管道到 Out-FileSet-Content 使用 -Encoding 参数代替.

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.

不幸的是,没有补充的 ConvertTo-StringData,因此您必须创建自己的输出格式(哈希表的默认输出格式不能用作属性文件):

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 返回一个哈希表,所以 $AppProps 包含一个.

  • ConvertFrom-StringData returns a hashtable, so $AppProps contains one.

$AppProps.GetEnumerator() 将哈希表的键/值对([System.Collections.DictionaryEntry] 类型的字典条目)一一发送管道.

$AppProps.GetEnumerator() sends the hashtable's key/value pairs (dictionary entries of type [System.Collections.DictionaryEntry]) one by one through the pipeline.

  • .GetEnumerator() 调用是必要的,因为 PowerShell 将哈希表视为管道中的单个对象.
  • The .GetEnumerator() call is necessary, because PowerShell treats a hashtable as a single object in a pipeline.

% { "$($_.Name)=$($_.Value)" } 为每个键/值对构造输出字符串.

% { "$($_.Name)=$($_.Value)" } constructs the output string for each key/value pair.

警告源于使用 ConvertFrom-StringData 读取属性文件:

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.

这篇关于如何在 powershell 中编辑 .property 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆