首页 > 解决方案 > 在 Powershell 中解析字符串并创建一个表

问题描述

我在 Powershell 中有一个变量,它返回以下字符串

    S: Title = test S: Title = test2 S: Title = test3 S: Title = test4 
 TE: 2019-01-19T00:00:00Z TE: 2019-01-20T00:00:00Z TE: 2019-01-22T00:00:00Z TE: 2019-01-23T00:00:00Z

我正在尝试将此字符串格式化为(即使在 csv 文件中):

test        test2        test3       test4
2019-01-19  2019-01-20   2019-01-22  2019-01-23

但没有成功。我怎样才能做到这一点?

编辑:这是生成字符串的行。基本上我想提取keepass数据库中所有条目的名称和到期日期(我可能找到了另一种使用导出的xml文件的方法):

$entries = & "$kps" -c:ListEntries "$kdbx" -pw:$pass

标签: stringpowershellparsing

解决方案


我不得不承认这有点过度使用,.replace()但没有太多可使用的:

$mystring= "    S: Title = test S: Title = test2 S: Title = test3 S: Title = test4 
 TE: 2019-01-19T00:00:00Z TE: 2019-01-20T00:00:00Z TE: 2019-01-22T00:00:00Z TE: 2019-01-23T00:00:00Z "


$MyString.trim().replace(" S: Title = ",",").replace("T00:00:00Z TE: ",",").replace("TE: ","").replace("S: Title = ","").replace("T00:00:00Z","").replace(" ","") | convertfrom-csv

输出:

test         test2        test3        test4     
----         -----        -----        -----     
2019-01-19   2019-01-20   2019-01-22   2019-01-23

在创建字符串时实施这些步骤会更容易(并且更容易监督)。


推荐阅读