powershellconvertto-json

Powershell batch of commands response into JSON


I'm trying to capture a list of users and groups on my windows host. I can capture the user and groups info and assign them to varaibles $users and $groups with the following commands:

    $groups=$(Get-WmiObject win32_group | Select Name | Sort Name); $users=$(Get-WmiObject -Class Win32_UserAccount | Select Name | Sort Name)

What I can't figure out is how to pass these to the ConvertTo-JSON function where they each get their own keys i.e, I'd like the response to look like this:

{
    "users": ["john", "geroge", "ringo"],
    "groups": ["drums", "guitar"]
}

I have tried a few variations of this, but can't quite get the correct syntax for powershell and the ConvertTo-JSON function.

    $jsonBlob=$(\"groups\" : $(groups), \"users"\ : $(users); ConvertTo-Json $jsonBlob;

Any suggestions on how to achieve this?


Solution

  • Create a PSCustomObject and Pipe that to ConvertTo-Json

    $groups = Get-WmiObject -Class Win32_Group | Sort-Object Name
    $users = Get-WmiObject -Class Win32_UserAccount | Sort-Object Name
    $jsonBlob = [PSCustomObject]@{"users" = $users.Name;"groups" = $groups.Name} | ConvertTo-Json