arrays - 如何将数组添加到数组或在 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.
}
这个函数返回一堆代表电子邮件及其属性的数组,我想:
- 立即解包,以便我可以将它们放入数据库
- 打包成一个数组并添加到一个数组/列表以传递给一个函数,该函数将解包并检查/插入数据库。
问题是我似乎无法弄清楚如何将我的函数吐出的数组放入数组中,以便在吐出时解包或解包数组,以便我可以将它们插入表中。
如果我试图以 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...}
我究竟做错了什么?
解决方案
如果您要使用大型数组,请考虑使用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
如果需要)。
推荐阅读
- php - 如何将变量名从控制器传递到 Symfony 中的树枝文件?
- android-recyclerview - Android RecyclerView notifyItemRangeChanged 正在替换旧数据
- r - 如何在 R 中标记散点图的点?
- javascript - 将公用文件夹中的 css 导入任何反应组件
- python - 如何让我的机器人更快地播放音频?(discord.py 重写)
- api - Garmin 连接 OAuth 用户访问令牌 签名方法 HMAC-SHA1 的签名无效
- c# - Unity - 发现多个文件具有独立于操作系统的路径 'META-INF/androidx.lifecycle_lifecycle-runtime.version' 有关详细信息,请参阅控制台
- javascript - 在 getElementsByTagName 循环中操作标签
- c# - 如何将集合传递给 husky 以在预提交时运行多个操作?
- php - IIS上的PHP exec无法通过Web浏览器工作