【问题标题】:Powershell: How to deal with values of grouped objects?Powershell:如何处理分组对象的值?
【发布时间】:2019-02-07 01:22:02
【问题描述】:

我有一个包含两列的 excel 列表,如下所示:

Excel文件

+--------+------------+
| File   | Email      |
+--------+------------+
| 0001   | A@mail.com |
| 0004   | B@mail.com |
| 0005   | C@mail.com |
| 0008   | B@mail.com |
+--------+------------+

我想使用 PowerShell 脚本向每个用户发送电子邮件并附加与特定用户相关的所有文件。例如,用户A 只会得到一个文件(c:\temp\0001.pdf),用户B 会得到两个附加到他的电子邮件的文件(c:\temp\0004.pdf 和 c:\temp\0008.pdf)等等开。

我可以使用 powershell 模块 ImportExcel 读取我的 excel 文件,并按电子邮件地址对内容进行分组。而且我还可以在不同的 powershell 脚本中发送一封电子邮件。但我不知道如何链接这两个代码 sn-ps,因为我是 powershell 初学者。任何帮助将不胜感激。

代码部分 1

$exceldata = (Import-Excel -Path "C:\Users\Administrator\Desktop\testdata.xlsx")
$groupeddata = ($exceldata | Group-Object -Property Email)

我得到的结果集如下

+-------+------------+------------------------------------------------------------------+
| Count | Name       | Group                                                            |
+-------+------------+------------------------------------------------------------------+
| 1     | A@mail.com | {@{File=0001; Email=A@mail.com}}                                 |
| 2     | B@mail.com | {@{File=0004; Email=B@mail.com}, @{File=0008; Email=B@mail.com}} |
| 1     | C@mail.com | {@{File=0005; Email=C@mail.com}}                                 |
+-------+------------+------------------------------------------------------------------+

代码部分 2

Send-MailMessage -To "B@mail.com" -From "DB Admin <dbadmin@xyx.com>" -SMTPServer smtp1.xyz.com -Subject "Monthly report" -Body "Please check attached files" -Attachments "c:\temp\0004.pdf", "c:\temp\0008.pdf"

同样有效。

但是我怎样才能链接这两个代码sn-ps?非常感谢任何帮助,因为我是 Powershell 脚本初学者。

【问题讨论】:

    标签: powershell email foreach


    【解决方案1】:

    考虑使用类似的方法让您的代码正常工作。我模拟了你的一些数据,但你可以看到$group 就像你的$groupeddata

    关键是查看调试器中的数据结构,并弄清楚如何访问所需的成员。在每个条目上使用foreach,让您可以对组中的每个条目进行操作。

    $data = @'
    File, Email
    0001, A@email.com,
    0004, B@email.com,
    0005, C@email.com,
    0008, B@email.com,
    '@
    
    $xls = $data | ConvertFrom-Csv
    
    $group = $xls | Group -Property Email
    
    foreach ($entry in $group)
    {
        $email = $entry.Name
        $files = ($entry.Group.File | % {'c:\temp\'+$_+'.pdf'}) -join ', '
    
        # debugging...look at this in debugger ISE or VSCode
        "$email and $files"
    
        # uncomment to actually run the command...
        #Send-MailMessage -To $email -From "DB Admin <dbadmin@xyx.com>" -SMTPServer smtp1.xyz.com -Subject "Monthly report" -Body "Please check attached files" -Attachments $files
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      相关资源
      最近更新 更多