使用Powershell读取和解析Strucutred文本文件

时间:2018-02-13 16:05:50

标签: string powershell parsing string-parsing

我正在尝试读取从其他程序生成的文本文件并解析它们以执行其他操作。

This主题很接近,但我正在阅读的文件因缺少更好的单词而有更多“结构化”。以下是我正在阅读的文件的样本供参考:

data:extend(
{
{
type = "buildformula",
name = "item1",
active = false,
buildtime = 3,
ingredients =
{
  {"ingredient1", 1},
  {"ingredient2", 4},
  {"ingredient3", 5}
},
result = "finished item 1"
},        

{
type = "buildformula",
name = "item2",
active = true,
buildtime = 12,
ingredients =
{
  {"ingredient1", 2},
  {"ingredient2", 3}
},
result = "finished item 2"
},
}
)

另一个建议是在帖子中引用了ConvertFrom-String命令,它似乎具有我需要的功能,但我仍然没有得到任何结果。

最后这是我最近的代码:

    $TemplateAdr = @'
{
type = "buildformula",
name = "item1",
active = false,
buildtime = 3,
ingredients =
{
  {"ingredient1", 1},
  {"ingredient2", 4},
  {"ingredient3", 5}
},
result = "finished item 1"
},        

{
type = "buildformula",
name = "item2",
active = true,
buildtime = 12,
ingredients =
{
  {"ingredient1", 2},
  {"ingredient2", 3}
},
result = "finished item 2"
},
'@
$output=Get-Content -Path "C:\temp\itembuilds.txt" |  ConvertFrom-String -TemplateContent $TemplateAdr

我是PowerShell的新手,但我觉得这是可能的。

1 个答案:

答案 0 :(得分:1)

您的$TemplateAdr模板未标记为此类。

试试这个:

$TemplateAdr = @'
data:extend(
\{
\{
type = "{Type*:buildformula}",
name = "{Name:item1}",
active = {[bool]Active:false},
buildtime = {[int]BuildTime:3},
{Ingredients:ingredients =
\{
  \{"{IngredientName*:ingredient1}", {[int]IngredientCount:1}\},
  \{"{IngredientName*:ingredient2}", {[int]IngredientCount:4}\},
  \{"{IngredientName*:ingredient3}", {[int]IngredientCount:5}\}
\},}
result = "{[string]Result:finished item 1}"
\},

\{
type = "{Type*:buildformula}",
name = "{Name:item2}",
active = {[bool]Active:true},
buildtime = {[int]BuildTime:12},
{Ingredients:ingredients =
\{
  \{"{IngredientName*:ingredient1}", {[int]IngredientCount:2}\},
  \{"{IngredientName*:ingredient2}", {[int]IngredientCount:3}\}
\},}
result = "{[string]Result:finished item 2}"
\},
\}
)
'@

Get-Content -Path "C:\temp\itembuilds.txt" |
    ConvertFrom-String -TemplateContent $TemplateAdr |
        Select-Object -Property Type,Name,Active,BuildTime,@{Name='Ingredients';Expression={$_.Ingredients.Items}}

使用\转义大括号。我已经为某些属性明确指定了PowerShell类型(您可能不希望这样)。我已使用Select-Objectingredients列表映射到新媒体资源。

随意更改字段规范({PropertyName:whatever})中的属性名称。