我正在尝试读取从另一个程序生成的文本文件并解析它们以执行其他操作。
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 新手,但我觉得这是可能的。
最佳答案
您的 $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-Object
将 ingredients
列表映射到新属性。
您可以随意更改字段规范内的属性名称 ({PropertyName:whatever}
)。
关于string - 使用 Powershell 读取和解析结构化文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48770906/