如何使用powershell Foreach循环创建JSON负载



要求:通过发送网格帐户(发送网格API(通过附加多个附件发送电子邮件。

描述:我能够创建json有效载荷,并能够通过硬编码附件值以单个附件进行发送。我正在打开窗口窗体对话框,可以选择需要附加的单个/多个文件。

代码:

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{ 
InitialDirectory = [Environment]::GetFolderPath('Desktop') 
#Filter = 'Documents (*.docx)|*.docx|SpreadSheet (*.xlsx)|*.xlsx'
Filter           = 'All files (*.*)| *.*'
Title            = 'Select  File(s) for Attachments'
Multiselect      = $true
}
$FileBrowser.ShowDialog() | Out-Null
$FilesEncodedContents = New-Object System.Collections.ArrayList
$AttachmentsjsonRequest = @()
if ($FileBrowser.FileNames.Count -gt 0) {
foreach ($file in $FileBrowser.FileNames) {
[string] $filerawContent = $null
$filedetails = Get-Item $file
$filerawContent = ConvertToBase64Encode $file
if (![string]::IsNullOrWhitespace($filerawContent)) {
$FilesEncodedContents.Add($filerawContent) 
$obj = New-Object -TypeName PSObject
$obj | Add-Member -MemberType NoteProperty -Name filename -Value (Get-Item $file).Name
$obj | Add-Member -MemberType NoteProperty -Name content_id -Value (Get-Item $file).Name
$obj | Add-Member -MemberType NoteProperty -Name content -Value $filerawContent
$obj | Add-Member -MemberType NoteProperty -Name disposition -Value 'attachment'
$AttachmentsjsonRequest += $obj
}
}
}    
Write-Host "$AttachmentsjsonRequest"
$headers = @{ }
$headers.Add("Authorization", "Bearer $ApiKey")
$headers.Add("Content-Type", "application/json")
$jsonRequest = [ordered]@{
personalizations = @(@{to = @(@{email = "$MailTo" })
subject               = "$Subject" 
})
from             = @{email = "no-reply@xxx.com" }
attachments      = "$AttachmentsjsonRequest"
content          = @( @{ type = "text/plain"
value            = "Sample Mail Body" 
}
)
} | ConvertTo-Json -Depth 100
Write-Host $jsonRequest | ConvertTo-Json -Depth 100
Invoke-RestMethod   -Uri "https://api.sendgrid.com/v3/mail/send" -Method Post -Headers 
$headers -Body $jsonRequest
Write-Host "Mail Sent"

#region ConvertToBase64Encode
Function ConvertToBase64Encode([string] $AttachementFile) {
[string] $fileContentEncoded = $null
if (Test-Path $AttachementFile -PathType leaf) {
$fileContent = get-content $AttachementFile
$fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$fileContentEncoded | set-content ((Get-Item -Path $AttachementFile).Name + ".b64")
}
else {
$fileContentEncoded = $null
Write-Host "File : $FileAttachment not exists,skipping and continue to add if any other 
attachments  uploaded"
}
return $fileContentEncoded
}
#endregion

问题:[更新]

尝试上传单个或多个附件后出现以下错误

{"errors":[{"message":"Invalid type. Expected: array, given: string.","field":"attachments","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.attachments"}]} .

参考链接:发送网格API文档:

https://sendgrid.com/docs/API_Reference/api_v3.html

我的建议是考虑不要将JSON构建为文本,首先构建一个Powshell对象,用ConvertTo-Json将其转换为JSON。

使用此方法,数组将在JSON中正确表示。不要忘记设置-DEPTH参数。

attachments array[object] An array of objects in which you can specify any attachments you want to include.

所以在您的Powershell对象中,attachments将是一个@()

具有内容、类型、文件名、处置、content_id属性的对象的。

我最近深入了解了错误细节。它在JSON负载中给出了提示,"attachments"字段显示为字符串,而不是数组对象,这是通过在"$jsonrequest">变量中向attachmentjsonrequest添加@(@(((来修复的。

简而言之:">attachmentjsonrequest是一个数组对象,需要使用@((转换为JSON负载

感谢您建议使用数组对象。

attachments      = @(@($AttachmentsjsonRequest))

相关内容

  • 没有找到相关文章

最新更新