使用Powershell解析变量

时间:2016-01-18 03:38:46

标签: regex powershell

我有通过我的电子邮件的脚本,然后返回与我的查询匹配的每封电子邮件的正文。身体看起来像这样

Recipients:     last.first@email-place.com 
Attachment  Report.pdf 
Timestamp of Message:   18 January 2016 

Recipients:     Anothername.first@email-place.com 
Attachment  Report2.pdf 
Timestamp of Message:   18 January 2016 

我试图在自定义对象中获取正文的每一行,或者只是将电子邮件地址提取到变量以进行更多工作。 任何想法。

1 个答案:

答案 0 :(得分:3)

一种选择是使用多行正则表达式捕获数据,然后从捕获中创建自定义对象:

编辑:使用ForEach循环更新了示例。

$regex = @'
(?ms)Recipients:\s+(.+?)\s* 
Attachment\s+(.+?)\s* 
Timestamp of Message:\s+(.+)
'@ 

$Result=
ForEach ($text in $variable)
 {
   if ($text -match  $regex)
     {
       [PSCustomObject]@{
        Recipients = $matches[1]
        Attachment = $matches[2]
        Timestamp  = $matches[3]
        }
     }
 }

Recipients                        Attachment  Timestamp      
----------                        ----------  ---------      
Anothername.first@email-place.com Report2.pdf 18 January 2016