如何使用Power Shell Foreach循环创建JSON有效负载

问题描述 投票:0回答:1

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

Description:我能够创建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

  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) 

        $AttachmentsjsonRequest = @{      

          attachments = @(@{ type = "text/plain"
              filename            = (Get-Item $file).Name
              disposition         = "attachment"
              content_id          = (Get-Item $file).Name
              content             = "$filerawContent" 
            })
        } | ConvertTo-Json -Depth 100
      }
    }
  }    
      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 = "[email protected]" }
  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  

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

问题:

因此,无论是否具有硬编码值,我都可以使用单个附件发送,但是当我尝试使用JSON净荷发送多个附件时。我遇到了以下错误。

1)我在“ $ jsonRequest”变量

中两次获得附件单词
     "attachments": "{\r\n  \"attachments\": [\r\n    {\r\n     

2)每当我选择多个文件$$ AttachmentsjsonRequest变量数据仅显示单个文件。如何为每个附件文件数据多次循环json有效负载。

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

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

json powershell email sendgrid sendgrid-api-v3
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.