jsonpowershellpowershell-cmdlet

Adding a key-value pair to a JSON object in Powershell without using ConvertFrom-Json


Is there a way to add a key-value pair to a JSON object in Powershell without using the ConvertFrom-Json cmdlet? The script I currently have outputs a JSON file that is unreadable because it has several parent objects, but I want to merge all of the parent objects into one. However, I am unsure how to do that since, I have tried creating one parent object to use for all functions, but I receive an error when I try to convert the JSON object to a PSObject.

Here is a piece of my JSON file:

{
  "HostName": "MMuns-L2314"
}
{
  "SerialNumber": "BNW35Y3"
}
{
  "LatestUptime": "2025-06-10T11:54:17.5000000-04:00"
}

but I want it to look like this:

{
  "HostName" : "MMuns-L2314",
  "SerialNumber" : "BNW35Y3",
  "LatestUptime" : "2025-06-10T11:54:17.5000000-04:00"
}

Additionally, here are the functions I have initially used that pulls and then adds the information to JSON:

Function Get-Hostname { 
  $hostname = hostname
  $hostObj = @{
    HostName = $hostname
  }
  $hostJSON = $hostObj | ConvertTo-Json
  $hostJSON | Out-File -FilePath "$HOME/Downloads/serverscript.json"


}

Function Get-SerialNumber { 
  $SerialNumber = (Get-CimInstance Win32_BIOS).SerialNumber
  $serialObj = @{
    SerialNumber = $SerialNumber
  }
  $serialJSON = $serialObj | ConvertTo-Json
  Add-Content -Path "$HOME\Downloads\serverscript.json" -Value $serialJSON
}

Function Get-Upt { 
  $upt = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToString('o')
  $uptObj = @{
    LatestUptime = $upt
  }
  $uptJSON = $uptObj | ConvertTo-Json
  Add-Content -Path "$HOME\Downloads\serverscript.json" -Value $uptJSON
}

Finally, when I pipe a json object (i.e. '$hostJson') to the ConvertFrom-Json cmdlet, I get a null output and an error telling me that I am "unable to bind" the output to a variable:

ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:24 char:25
+   $hostJSON = $hostJSON | ConvertFrom-Json

Solution

  • 1 PowerShell object/hashtable = 1 JSON object.

    In other words, if you want a JSON document consisting of a single object with those 3 properties, then you'll want to create exactly one object in PowerShell and then convert that to JSON at once:

    $wholeObject = [ordered]@{
      HostName = hostname
      SerialNumber = (Get-CimInstance Win32_BIOS).SerialNumber
      LatestUptime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToString('o')
    }
    
    # this will now produce the expected output
    $wholeObject |ConvertTo-Json