Home > other >  Powershell creating pscustomobject object
Powershell creating pscustomobject object

Time:10-20

I need some urgent help on something I really can't figure out.

I have a file containing loads of these ID's

enter image description here

I need to create a json payload in powershell to look like this containing each of these ID's

{
  "assetIds": [
    "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "f86354c4-8e69-4cee-b85c-11b9534019e0",
    "6829c1ad-17d8-4d9c-93c7-2a4b6acfc201"
  ],
  "sendNotification": true
}

Any help on this will be great!

CodePudding user response:

Fairly straightforward:

# define object
$object = [pscustomobject]@{
  assetIds = @(
    Get-Content path\to\file.txt
  ) -as [string[]]
  sendNotification = $true
}

# convert to JSON
$object |ConvertTo-Json

The @() (the "subexpression operator") ensures the value of the assetIds property will always be an array (even if Get-Content returns 0 or only 1 ID)

The -as [string[]] conversion prevents PowerShell from serializing extended properties that might have been attached to the strings by Get-Content

  • Related