1

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?

Coder Jones
  • 93
  • 1
  • 4

2 Answers2

0

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
jfrmilner
  • 1,458
  • 10
  • 11
0

I would recommend using DirectorySearcher to look up users and groups. It will be more efficient and focused on just the name.

$usearcher = [adsisearcher]'(&(objectCategory=User)(objectclass=person))'
$gsearcher = [adsisearcher]'(objectCategory=group)'

$usearcher.PropertiesToLoad.Add("name")
$gsearcher.PropertiesToLoad.Add("name")

$usearcher.SizeLimit = 1000
$gsearcher.SizeLimit = 1000

$obj = [pscustomobject]@{
           users  = $usearcher.FindAll() | % { $_.properties['name'][0] } 
           groups = $gsearcher.FindAll() | % { $_.properties['name'][0] }
           }

$json = $obj | ConvertTo-Json

This will run on the local domain of the account you are using to run this.

Jawad
  • 11,028
  • 3
  • 24
  • 37
  • Thanks, I'll look into this. I've accepted the other answer, but I suspect this will also help with what I'm trying to do. – Coder Jones Feb 20 '20 at 11:31
  • @coderJones I would recommend you try the solutions and see which functions better and which serves as a better answer for other readers as well. – Jawad Feb 22 '20 at 03:20