如何在 Powershell 中分组和过滤 Sharepoint 网络服务 XML 响应

How to group and filter Sharepoint webservice XML response in Powershell

我需要根据 Sharepoint 列表发送自动电子邮件。我能够检索响应并拥有发送电子邮件的代码。但是电子邮件正文需要是动态的并且需要对响应日期进行分组。我正在考虑将服务响应转换为表示为哈希图并使用该哈希图发送有针对性的电子邮件。以下是服务响应示例:

  <rs:data ItemCount="10">
     <z:row ows_Owner='1111@xxx.com' ows_Stories='Story1' ows_Program='Program1' />
     <z:row ows_Owner='1111@xxx.com' ows_Stories='Story2' ows_Program='Program1' />
     <z:row ows_Owner='1111@xxx.com' ows_Stories='Story3' ows_Program='Program2' />
     <z:row ows_Owner='1111@xxx.com' ows_Stories='Story4' ows_Program='Program2' />
     <z:row ows_Owner='2222@xxx.com' ows_Stories='Story5' ows_Program='Program1' />
     <z:row ows_Owner='2222@xxx.com' ows_Stories='Story6' ows_Program='Program1' />
     <z:row ows_Owner='2222@xxx.com' ows_Stories='Story7' ows_Program='Program1' />
     <z:row ows_Owner='2222@xxx.com' ows_Stories='Story8' ows_Program='Program2' />
     <z:row ows_Owner='2222@xxx.com' ows_Stories='Story9' ows_Program='Program2' />
     <z:row ows_Owner='2222@xxx.com' ows_Stories='Story10' ows_Program='Program2' />
  </rs:data>

什么是使用 powershell 对上述数据进行分组和迭代的最佳方法,以发送正文包含 'Stories' 按 'Program' 分组的消息的电子邮件。例如:发送至“1111@xxx.com”的电子邮件的邮件正文为:

更新: 这是伪代码,可以更好地解释我的要求 -

select unique $owners from rs:row

foreach $owner in $owners
{     $messageBody =""
    foreach $program in rs:row where ows_owner=$owner
    {
        $messageBody += $program "<br />
        foreach $story in rs:row where ows_owner=$owner and ows_program=$program
        $messageBody += $story "<br />
     }
         sendmail $owner, $messageBody 
}    

只需要代码即可在 powershell 中轻松实现这一点,尤其是根据 'owner' 和 'program' 属性过滤数据

我将从 <row> 节点创建自定义 PowerShell 对象,然后使用 Group-Object 按程序对它们进行分组:

[xml]$xml = Get-Content 'C:\path\to\input.xml'

$nsm = New-Object Xml.XmlNamespaceManager($xml.NameTable)
$nsm.AddNamespace('rs', 'http://...')  # replace with correct namespace URI

$xml.SelectSingleNode('//rs:data', $nsm) | select -Expand row | % {
  New-Object -Type PSCustomObject -Property @{
    Program = $_.ows_Program
    Story   = $_.ows_Stories
  }
} | group Program | select Name, @{n='Stories';e={$_.Group.Story}}

如果分组不是一个选项,您可以像这样构建嵌套哈希表的数据结构:

$data = @{}
$xml.SelectSingleNode('//rs:data', $nsm) | select -Expand row | % {
  New-Object -Type PSCustomObject -Property @{
    Owner   = $_.ows_Owner
    Program = $_.ows_Program
    Story   = $_.ows_Stories
  }
} | % {
  if (-not $data.Contains($_.Owner)) {
    $data[$_.Owner] = @{ $_.Program = @() }
  } elseif (-not $data[$_.Owner].Contains($_.Program)) {
    $data[$_.Owner][$_.Program] = @()
  }
  $data[$_.Owner][$_.Program] += $_.Story
}