首页 > 解决方案 > 如何将数组添加到数组或在 PowerShell 中解压缩动态生成的数组?

问题描述

我的函数为我收件箱中的每封电子邮件输出一个数组。我想要么将它们添加到列表中进行解包,要么动态解包它们以将值用作 SQL 查询中的字符串。

我已经编写了我的函数并验证了它是否按照我的预期返回数组,并尝试了 |s ForEach-Object、ForEach 等。

就像在 PowerShell 中一样,函数是:

Function Get-OutlookInBox
{
    Add-type -assembly “Microsoft.Office.Interop.Outlook” | out-null
    $olFolders = “Microsoft.Office.Interop.Outlook.olDefaultFolders” -as [type]
    $outlook = new-object -comobject outlook.application
    $namespace = $outlook.GetNameSpace(“MAPI”)
    $folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
    #Is an array now I just need to break down this array into constituent parts so i can DB these hoes.
    return $message = $folder.items | Select-Object -Property SenderName, Subject, SentOn, ReceivedTime, BCC.
}

这个函数返回一堆代表电子邮件及其属性的数组,我想:

  1. 立即解包,以便我可以将它们放入数据库
  2. 打包成一个数组并添加到一个数组/列表以传递给一个函数,该函数将解包并检查/插入数据库。

问题是我似乎无法弄清楚如何将我的函数吐出的数组放入数组中,以便在吐出时解包或解包数组,以便我可以将它们插入表中。

如果我试图以 python 方式执行此操作,它看起来像:

listOfEmailes = list()
for x in GetOutlookEmails():
    listOfEmails.appened(x)

for email in listOfEmails:
    sender =  emails[0]
    Sent = emails[1]
    received = emails[2]
    BCCs = emails[3]
# Craft SQL string here with substitution
sqlquery = blah
# Execute crafted SQL query here.
dosql(sqlquery)

我的想法是,如果我要做类似的事情

$EmailProperties = @{}
$Inbox = Get-OutLookInbox

ForEach ($message in $Inbox)
{
     $EmailProperties.add($Message)
}

结果数组看起来像:

@{ @{array1}, @{array2}, @{array3}, etc...}

我究竟做错了什么?

标签: arrayssql-serverpowershelloutlook

解决方案


如果您要使用大型数组,请考虑使用System.Collections.Generic.List. 添加到普通数组具有复制数组的副作用,这可能导致不必要的内存使用。在此处使用您的伪代码作为道具):

$Inbox = Get-OutLookInbox
$EmailProperties = New-Object System.Collections.Generic.List[System.Collections.Hashtable]( $Inbox.count )

ForEach ( $message in $Inbox )
{
    $EmailProperties.add(@{
      PropertyOne = $message.SomeProp
      PropertyTwo = $message.SomeOtherProp
      AnyColourYouLike = $message.DarkSideOfTheMoon
      IThinkYouGetIt = $message.HeGetsIt
    })
}

如果您更喜欢PSCustomObject而不是哈希表,请将 List 类型更改为PSCustomObject并通过更改上述调用Hashtable的第一行来强制转换为:.add

$EmailProperties.add([PSCustomObject]@{

也就是说,根据您的问题,目前尚不清楚您要在这里做什么。您已经返回了一个数组,您实际上是在尝试将哈希表添加到数组中吗?如果我不在基地,请澄清你的问题。

编辑:假设您需要HashTable电子邮件对象的属性,我对此进行了一些更改。

编辑 2:添加了如何使它作为一个数组工作(PSCustomObject如果需要)。


推荐阅读